/*
模块名称：处方打印
起始日期：2021-5-23
功能描述：
1.自动检索可打印处方，打印输出。
2.指定收据号进行处方打印。
业务逻辑：
1.
2.通过 invoice_no （发票号）查询 fin_opb_feedetail/sun_recipe_pr ,获取处方药品项目基本信息。
通过recipe_no（处方号） 关联 met_ord_recipedetail ,获取处方诊断,医师姓名
通过 clinic_code（门诊唯一编号）查询 fin_opr_register 获取处方头信息。

*/
#include "tj_dialog_cfdy.h"
#include "ui_tj_dialog_cfdy.h"
#include "tj_bill_list_output.h"
#include "pub_var.h"
#include <QSettings>
#include <QPrinter>
#include <QPrinterInfo>
#include <QDebug>
#include <QMessageBox>
#include <QMap>
#include <QMapIterator>
#include <QDate>
#include <QDateTime>
#include <QPen>
#include <QVector>
#include <QFontMetrics>
#include <QSqlError>
#include <QTextCodec>
#include <QFile>
#include <QImage>
#include <QBitmap>
#include <QColor>
#include <QComboBox>
#include <QAxWidget>
#include <QProcess>
#include <QBuffer>
#include <QDir>

//using namespace tj_bill_list_output;

Dialog_cfdy::Dialog_cfdy(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_cfdy)
{

    ui->setupUi(this);
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    qro_undrug0 = new QSqlQuery(pub::db_o);
    qro_undrug1 = new QSqlQuery(pub::db_o);

    QSettings setIni("clin.ini", QSettings::IniFormat);
    terminalCode = setIni.value("cfdy/terminal").toString();    //当前工作窗口代码

    QString undrug_list_ini = setIni.value("cfdy/undrug_dept").toString();    //需要输出的非药品窗口
    QStringList undrug_list = undrug_list_ini.split("^");

    undrug_dept = "'undrug_dept'";

    foreach (QString s, undrug_list)
    {
        undrug_dept += ",'" + s + "'";
    }

    //准备工作终端列表
    qro->exec("select t_name, t_code , dept_code from pha_sto_terminal where t_type = '0'");
    while(qro->next())
    {
        ui->cbbTerminal->addItem(qro->value(0).toString());
        if( qro->value(1).toString() == terminalCode )
        {
            terminalName = qro->value(0).toString();    //当前窗口代码对应的名称
            deptCode = qro->value(2).toString();    //
        }
    }

    //当前工作打印机
    cfPrinter = setIni.value("cfdy/printer").toString();

    bzPrinter = setIni.value("bz/printer").toString();

    //显示当前工作终端
    ui->cbbTerminal->setCurrentText(terminalName);

    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/cfdy").toRect();
    this->setGeometry(rct);
    this->setWindowFlags(Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);

    //接收默认事件的按钮不显示
    ui->pushButton->setVisible(false);
    ui->pushButton_2->setVisible(false);  //temporary function

    //ui->ckb_undrug->setEnabled(false);//默认治疗处方打印

    //定时器，用于自动打印处方
    tm = new QTimer(this);
    connect(tm, SIGNAL(timeout()), this, SLOT(onTimerOut()));

    //定时器，用于延时打印非药品处方
    tm_print_undrug = new QTimer(this);
    tm_print_undrug->setSingleShot(true);
    connect(tm_print_undrug, &QTimer::timeout, this, &Dialog_cfdy::tm_print_undrug_timer);

    //打印机设置
    prt= new QPrinter(QPrinter::HighResolution); // :ScreenResolution  HighResolution
    prt->setPrinterName(cfPrinter);

    qrm->prepare("select p_width,p_height from com_printer_setting "
                 " where p_type = '处方' and p_item = '页面'");
    qrm->exec();
    int w = 0, h = 0;

    if(qrm->next())
    {
        w = qrm->value(0).toInt();
        h = qrm->value(1).toInt();
    }
    else
    {
        QMessageBox::information(this,"错误","处方打印参数缺失！");
    }

    if( w<30 || h<30 )
    {
        QMessageBox::information(this,"错误","处方打印参数错误：页面数据无效！");
        w = 130 ;
        h = 248;
    }

    //打印机修正参数。不同打印机以相同数据输出，实际大小有差异，以此参数修正
    float printerScale = setIni.value("cfdy/scale").toDouble();
    int dotPerInch = prt->physicalDpiX();
    ptScale = double(dotPerInch) / 25.4 * printerScale;

    //设置纸张大小
    QSizeF sz = QSizeF(w , h);
    QPageSize psz(sz, QPageSize::Millimeter, "mzcf", QPageSize::ExactMatch);//  ::FuzzyMatch);Millimeter
    prt->setPageSize(psz);


    prt->setOrientation(QPrinter::Portrait);      // 纵向打印
    prt->setFullPage(true);
    pnt = new QPainter();

    ui->lwYfy->setFont(this->font());
    ui->pbTf->setEnabled(false);    //退费
    ui->pbTfzh->setEnabled(false);
    ui->pbBldy->setEnabled(false);    //病历
    ui->pb_bill_list_output->setEnabled(false);//费用清单
    ui->pbSinglePrint->setEnabled(false);    //处方

    connect(ui->cbbTerminal, SIGNAL(currentTextChanged(QString)), this, SLOT(cbbTerminalTextChanged(QString)));
    count = 0;

    QString sq = " select name from com_privileges  where role_dept = '调剂室' and type = 'role'";

    pub::fillCombo(ui->cbbCheck, sq, -1);
    pub::fillCombo(ui->cbbDelivery, sq, -1);

    zint_proc = new QProcess();

    acceptListClicked = true;//处方列表可接受点击

    barcode_return = new tj_form_barcode_return();

    //提示声音
    snd_new_recipe.setSource(QUrl("qrc:/snd/new_recipe.wav"));
    //设置音量
    snd_new_recipe.setVolume(0.9);
    //音效设置为单次播放，不循环
    snd_new_recipe.setLoopCount(0);

    jxc = new Form_qlsjsc();    //进销存上传

    jxc->open_log_file();

    timerCount = 0;
    stock_timer_count = 0;
}

Dialog_cfdy::~Dialog_cfdy()
{
    delete ui;
    delete zint_proc;
    delete barcode_return;
    delete pnt;
    delete prt;
    delete tm;
    delete jxc;
}

void Dialog_cfdy::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    tm->stop();
    QSettings setIni("clin.ini", QSettings::IniFormat);

    setIni.setValue("windowState/cfdy", QVariant(this->geometry()));

    qro->exec("select t_code from pha_sto_terminal where t_name = '" + ui->cbbTerminal->currentText() + "'");

    if(qro->next())
    {
        terminalCode = qro->value(0).toString();        //科室代码
    }

    setIni.setValue("cfdy/terminal",terminalCode);

    destroyW("dlg_cfdy");
}

void Dialog_cfdy::cbbTerminalTextChanged(QString arg1)
{
    qro->exec("select t_code ,dept_code from pha_sto_terminal where t_name = '" + arg1 + "'");

    if(qro->next())
    {
        deptCode = qro->value(1).toString();
        terminalCode = qro->value(0).toString();        //科室代码
        terminalName = arg1;

        qDebug()<<terminalCode<<terminalName;
    }
}

void Dialog_cfdy::on_pbExit_clicked()
{
    close();
}

void Dialog_cfdy::on_pbSinglePrint_clicked()
{
    if(ui->ckb_drug->isChecked())
    {
        print_single_recipe();
    }
    else
    {
        QMessageBox::information(this, "注意", "请勾选处方打印药品选项！");
    }

}

void Dialog_cfdy::print_single_recipe()
{

    QString sq, invoice_list = "'invoice_list'";

    if(!ui->rbF->isChecked())
    {
        //非发票号检索，通过 clinic_code 检索发票号
        sq = "select distinct invoice_no from fin_opb_feedetail where clinic_code = '";
        sq += clinicCode + "' and fee_code in ('001','002','003') ";
        sq += " and pay_flag = '1' and cancel_flag = '1'";
        qro->exec(sq);

        while(qro->next())
        {
            invoice_list += ",'" + qro->value(0).toString() + "'";
        }

        if( invoice_list == "'invoice_list'" )
        {
            QMessageBox::information(this,"错误","通过 clinic_code 找不到药品收据号！");
            return;
        }
    }
    else
    {
        invoice_list += ",'" + pub::add0(ui->leSjh->text().trimmed(),12) + "'";
    }

    //通过 invoice_no （发票号）查询 fin_opb_feedetail,获取处方药品项目基本信息。
    sq = "select item_name, specs, unit_price, qty, "//0-3
         " use_name, frequency_code, dose_once, dose_unit, base_dose, "//4-8
         " pack_qty, price_unit, recipe_no, clinic_code, "//9-12
         " invoice_no, DRUG_QUALITY, fee_code, days, oper_date"//13-17
         " from fin_opb_feedetail "
         " where invoice_no in (%1) and trans_type = '1' and drug_flag in('1','4') "
         " order by recipe_no, sequence_no";//
    sq = sq.arg(invoice_list);

    qDebug()<<"通过发票号查询 fin_opb_feedetail,获取处方药品项目基本信息";
    qDebug()<<sq;

    if(!qro->exec(sq))
    {
        qDebug()<<"sql error!"<<qro->lastQuery();
        return;
    }

    if(!qro->next())
    {
        qDebug()<<"sql has no value."<<qro->lastQuery();
        QMessageBox::information(this,"错误","找不到指定的收据号！");
        return;
    }

    QString recipe_no = qro->value("recipe_no").toString();
    sq = "select druged_oper, send_oper from pha_sto_recipe where recipe_no = '" + recipe_no + "'";
    qDebug()<<"提取已经打印处方药师信息："<<sq;
    qrot->exec(sq);
    qrot->next();

    if(!qrot->value(0).toString().isEmpty())
    {
        send_oper_code = qrot->value("send_oper").toString();
        druged_oper_code = qrot->value("druged_oper").toString();
    }

    //数据表内容导入内存
    QList<QMap<QString,QString>> rec;
    QMap<QString,QString> mp;

    QSet<QString> reci_list; //处方号列表

    while(true)
    {
        mp.clear();
        mp["item_name"] = qro->value(0).toString();
        mp["specs"] = qro->value(1).toString();
        mp["unit_price"] = qro->value(2).toString();
        mp["qty"] = qro->value(3).toString();   //数量
        mp["use_name"] = qro->value(4).toString();
        mp["frequency_code"] = qro->value(5).toString();
        mp["dose_once"] = qro->value(6).toString();
        mp["dose_unit"] = qro->value(7).toString();
        mp["base_dose"] = qro->value(8).toString();
        mp["pack_qty"] = qro->value(9).toString();  //包装数量
        mp["price_unit"] = qro->value(10).toString();  //划价单位 ， qty / pack_qty = 划价数量
        mp["recipe_no"] = qro->value(11).toString();
        mp["clinic_code"] = qro->value(12).toString();
        mp["invoice_no"] = qro->value(13).toString();
        mp["drug_quality"] = qro->value(14).toString();
        mp["fee_code"] = qro->value(15).toString();
        mp["days"] = qro->value(16).toString();
        mp["oper_date"] = qro->value(17).toDate().toString("yyyy-MM-dd");

        reci_list << qro->value(11).toString();

        rec << mp;

        if(!qro->next())
        {
            break;
        }
    }


    //保存处方状态，保存处方数据
    QSet<QString>::iterator it;

    for(it = reci_list.begin(); it != reci_list.end(); it++)
    {
        savePrintStatus(*it);
        //processData(*it);
    }

    if(!ui->ckb_drug->isChecked())
    {
        //选择不打印处方，直接返回
        snd_new_recipe.play();
        return;
    }

    QString currentRecipeNo = "";//当前处方号
    QString newRecipeNo = "";//新处方号
    double costCount = 0;   //处方金额
    double days_pack; //包装可用天数
    double days_item; //品种可用天数
    double days_item_1; //数量大于1的品种，数量减1个零售包装之后的可用天数
    int currentLine = 1;    //当前项目行数，1 - 5
    pnt->begin(prt);
    mpPage.clear(); //清空页面数据

    int count = 0;
    QString herb_usage = ""; //用法：
    bool has_herb = false;  //是否有草药
    int herb_last_line = 0;


    while(true)
    {
        newRecipeNo = rec[count]["recipe_no"] ;

        if(currentRecipeNo != newRecipeNo)  //处方号变更，提取处方头信息进行输出
        {
            //首次进入循环时 currentRecipe_no 为空，此时不打印，只赋值
            if(!currentRecipeNo.isEmpty())
            {
                //非首次进入,打印前一张处方

                if(has_herb)
                {
                    mpPage["草药" + QString::number(herb_last_line)] = herb_usage;
                }

                mpPage["金额"] = QString::asprintf("%.2f", costCount); //
                mpPage["recipe_no"] = rec[count-1]["recipe_no"];
                mpPage["clinic_code"] = rec[count-1]["clinic_code"];
                mpPage["invoice_no"] = rec[count-1]["invoice_no"];

                printPage();
                prt->newPage();     //处方号变更，换页
                mpPage.clear(); //清空页面数据
                currentLine = 1;    //行数
                costCount = 0;  //金额

                has_herb = false;

            }
            currentRecipeNo = newRecipeNo;  //

            if(rec[count]["fee_code"] == "003")
            {
                //草药处方
                sq = "select zd1,zd2,zd3,zyzd1,zyzd2,zyzd3,zyzh1,zyzh2,zyzh3"
                     " from ys_bz_e_rec"
                     " where clinic_code = '" + rec[count]["clinic_code"] + "'";
                //提取中医诊断
                qDebug()<<"提取中医诊断 : "<<sq;
                qrm->exec(sq);
                qrm->next();
                QString zyzd = qrm->value("zd1").toString()
                        + " / "
                        + qrm->value("zyzd1").toString()
                        + "[" + qrm->value("zyzh1").toString()
                        + "]";  //【】

                if(!qrm->value("zd2").toString().isEmpty())
                {
                    zyzd += qrm->value("zd2").toString() ;

                    if(!qrm->value("zyzd2").toString().isEmpty())
                    {
                        zyzd += " / "  + qrm->value("zyzd2").toString() ;
                    }

                    if(!qrm->value("zyzh2").toString().isEmpty())
                    {
                        zyzd += "[" + qrm->value("zyzh2").toString() + "]";
                    }
                }

                if(!qrm->value("zd3").toString().isEmpty())
                {
                    zyzd += qrm->value("zd3").toString() ;

                    if(!qrm->value("zyzd3").toString().isEmpty())
                    {
                        zyzd += " / "  + qrm->value("zyzd3").toString() ;
                    }

                    if(!qrm->value("zyzh3").toString().isEmpty())
                    {
                        zyzd += "[" + qrm->value("zyzh3").toString() + "]";
                    }

                }

                mpPage["临床诊断"] = zyzd;

                herb_usage.append(rec[count]["days"]);
                herb_usage.append("付，");
                herb_usage.append(rec[count]["use_name"]);    //用法
                herb_usage.append("，");
                herb_usage.append(rec[count]["dose_once"]);   //每次数量
                herb_usage.append(rec[count]["dose_unit"]);   //数量单位
                herb_usage.append("/");
                qrm->exec("select frequency_name, day_times from com_dict_frequency "
                          " where frequency_code = '"+rec[count]["frequency_code"]+"' ");

                if(!qrm->next())
                {
                    QMessageBox::information(this,"错误","提取 com_dict_frequency 数据无效！" + qrm->lastQuery());
                }
                herb_usage.append(qrm->value(0).toString());  //

            }
            else
            {
                //中成药，西药
                //通过recipe_no（处方号） 关联 met_ord_recipedetail ,获取处方诊断,医师姓名

                QString tmp_str = "select reci.doct_name, reci.clinicdiag_name, "//0,1
                                  " reci.clinicotherdiag1_name, reci.clinicotherdiag2_name, "//2,3
                                  " reci.doct_code , ck.check_doct_code"//4,5
                                  " from met_ord_recipedetail reci"
                                  " left join pha_sto_recipe_senior_check ck "
                                  "   on instr(ck.recipe_no, '%1' ) > 0 "
                                  " where reci.recipe_no = '%1'";
                tmp_str = tmp_str.arg(currentRecipeNo);
                qDebug()<<"获取处方诊断,医师姓名 : "<<tmp_str<<"\n";

                qro->prepare(tmp_str);
                //qro->bindValue(":recipe_no", currentRecipeNo);//使用newRecipeNo

                if(!qro->exec())
                {
                    QMessageBox::information(this,"error","从 met_ord_recipedetail 提取诊断信息错误!");
                    qDebug()<<qro->lastQuery();
                    break;
                }

                QStringList diagList;

                while(qro->next())
                {
                    mpPage["医师"] = qro->value(0).toString();

                    mpPage["senior_doct"] = qro->value("check_doct_code").toString();

                    mpPage["doct_code"] = qro->value("doct_code").toString();

                    if(!qro->value(1).toString().isEmpty() && diagList.indexOf(qro->value(1).toString()) < 0)
                    {
                        diagList << qro->value(1).toString();
                    }
                    if(!qro->value(2).toString().isEmpty() && diagList.indexOf(qro->value(2).toString()) < 0)
                    {
                        diagList << qro->value(2).toString();
                    }
                    if(!qro->value(3).toString().isEmpty() && diagList.indexOf(qro->value(3).toString()) < 0)
                    {
                        diagList << qro->value(3).toString();
                    }
                }
                qDebug()<<"diag list : "<< diagList<<" , diagList size is : "<< QString::number(diagList.size());

                if(diagList.size()<1)
                {
                    QMessageBox::information(this,"error","无法从 met_ord_recipedetail 找到对应的信息!");
                }
                else
                {

                    QString diag, zyzd;
                    for (int i = 0 ; i < diagList.size() ; i++)
                    {
                        if(i == 0)
                        {
                            diag += diagList[i];
                            zyzd = get_tr_diag( diagList[i], rec[count]["clinic_code"]);
                            if(!zyzd.isEmpty())
                            {
                                diag += " / " + zyzd;
                            }

                        }
                        else
                        {
                            diag += " ; " + diagList[i];
                            zyzd = get_tr_diag( diagList[i], rec[count]["clinic_code"]);
                            if(!zyzd.isEmpty())
                            {
                                diag += " / " + zyzd;
                            }
                        }
                    }

                    mpPage["临床诊断"] = diag;

                }

            }

            //通过 clinic_code（门诊唯一编号）查询 fin_opr_register 获取患者信息。
            //费别， 科室，日期，病志号，姓名，性别，年龄，
            qro->prepare("select pact_name, dept_name, trunc(reg_date) dt, card_no,"
                         "name, decode(sex_code , 'M', '男', 'F', '女') sex, birthday "
                         "from fin_opr_register where clinic_code = :cd");
            qro->bindValue(":cd",rec[count]["clinic_code"]);

            if(!qro->exec())
            {
                QMessageBox::information(this,"error","从 fin_opr_register 提取诊断信息错误!");
                qDebug()<<qro->lastQuery();
                break;
            }

            if(!qro->next())
            {
                QMessageBox::information(this,"error","从 fin_opr_register 找不到对应信息!");
                qDebug()<<qro->lastQuery();
                break;
            }

            mpPage["科别"] = qro->value("dept_name").toString();
            QDate dt = qro->value("dt").toDate();
            //mpPage["日期"] = dt.toString("yyyy-MM-dd");
            mpPage["日期"] = rec[count]["oper_date"] ;
            mpPage["病志号"] = qro->value("card_no").toString();
            mpPage["姓名"] = qro->value("name").toString();
            mpPage["性别"] = qro->value("sex").toString();
            dt = qro->value("birthday").toDate();

            QStringList ag = pub::getNl(dt.toString("yyyy-MM-dd"));
            mpPage["年龄"] = ag[0] + ag[1];
            //mpPage["处方标志"] = "普通";

            if(rec[count]["drug_quality"] == "P")
            {
                mpPage["处方标志"] = "精二";
            }else{
                mpPage["处方标志"] = "普通";
            }

            mpPage["费别"] = qro->value("pact_name").toString();
            mpPage["名头"] = pub::hos_name;
            mpPage["处方笺"] = "处 方 笺";

            //药师信息
            mpPage["druged_oper"] = druged_oper_code;
            mpPage["send_oper"] = send_oper_code;

        }

        if(rec[count]["fee_code"] == "003")
        {
            //中草药
            QString cur_item = rec[count]["item_name"] ;
            cur_item.append(" ");
            cur_item.append(QString::number(rec[count]["qty"].toUInt() / rec[count]["days"].toInt()));
            cur_item.append(rec[count]["price_unit"]);
            //cur_item.append("\t");
            cur_item.append("   ");

            int cur_line = (count / 4) + 1;
            mpPage["草药" + QString::number(cur_line)].append(cur_item);

            int i_sl = rec[count]["qty"].toUInt()  ;// 数量

            //金额累计
            costCount = costCount + double(qRound(i_sl * rec[count]["unit_price"].toDouble() * 100))/100;

            has_herb = true;
            herb_last_line = cur_line + 1;
        }
        else
        {
            //西药中成药
            mpPage["品名" + QString::number(currentLine)] = rec[count]["item_name"] ;

            QString price1 = QString::asprintf("%.1f", rec[count]["unit_price"].toDouble()); //保留1位小数
            QString price2 = QString::asprintf("%.2f", rec[count]["unit_price"].toDouble()); //保留2位小数
            QString price0 = qFuzzyCompare(price1.toDouble(), price2.toDouble()) ? price1 : price2;
            //保留1位小数和2位小数数值相等，输出1位小数形式，否则输出2位小数形式

            mpPage["price" + QString::number(currentLine)] = price0;
            mpPage["规格" + QString::number(currentLine)] = rec[count]["specs"];
            QString sl, yfyl;       //品种数量，用法用量, 字串，供打印用
            int i_sl = rec[count]["qty"].toUInt() / rec[count]["pack_qty"].toInt() ;// 品种数量，数值，供计算用
            sl = QString::number(i_sl) + rec[count]["price_unit"];
            costCount = costCount + i_sl * rec[count]["unit_price"].toDouble();     //金额累计
            yfyl = "用法：";
            yfyl.append(rec[count]["dose_once"]);   //每次数量
            yfyl.append(rec[count]["dose_unit"]);   //数量单位
            yfyl.append("  ");
            qrm->prepare("select frequency_name, day_times from "
                         "com_dict_frequency where frequency_code = :code ");
            qrm->bindValue(":code",rec[count]["frequency_code"]);

            if(!qrm->exec())
            {
                QMessageBox::information(this,"错误", "查询 com_dict_frequency 失败。"+qrm->lastQuery());
            }

            if(!qrm->next())
            {
                QMessageBox::information(this,"错误","提取 com_dict_frequency 数据无效！" + qrm->lastQuery());
            }

            yfyl.append(qrm->value(0).toString());  //每日用量
            yfyl.append("  ");
            yfyl.append(rec[count]["use_name"]);    //用法
            double days = qrm->value(1).toDouble();    //每日次数
            days_pack = rec[count]["base_dose"].toDouble() * rec[count]["pack_qty"].toDouble()
                    / rec[count]["dose_once"].toDouble() / days ;//最小包装可用天数
            days_item = days_pack * rec[count]["qty"].toDouble() / rec[count]["pack_qty"].toDouble(); //品种可用天数
            days_item_1 = days_item - days_pack; //减少一个包装之后的品种可用天数
            //qDebug()<<days_pack<<days_item;
            //qDebug()<<rec[i]["pack_qty"].toDouble()<<rec[i]["qty"].toDouble();
            QString bz = "";

            if(i_sl == 1)
            {
                //单包装,
                if(days_item > 7)
                {
                    //超门诊量
                    bz.append("*不拆零");//最小包装即超量，按“不拆零”处理
                }
            }
            else
            {
                if(days_item > 30)
                {
                    //超慢病量
                    if(days_item_1 > 30)
                    {
                        bz.append("*外出带药");
                    }
                    else
                    {
                        bz.append("*慢病,不拆零");
                    }
                }
                else
                {
                    if(days_item > 7)
                    {
                        //超门诊量
                        if(days_item_1 >= 7)
                        {
                            bz.append("*慢病用药");
                        }
                        else
                        {
                            bz.append("*不拆零");
                        }
                    }
                }
            }
            mpPage["备注" + QString::number(currentLine)] = bz;
            mpPage["数量" + QString::number(currentLine)] = sl;
            mpPage["用法用量" + QString::number(currentLine)] = yfyl ;
            currentLine ++ ; //项目行数量加 1
            //下一行预填充，如有正常值，此填充将被覆盖
            mpPage["品名" + QString::number(currentLine)] = "***以下空白***";

        }

        count++;
        if( count  >= rec.length())
        {
            //循环结束
            if(has_herb)
            {
                mpPage["草药" + QString::number(herb_last_line)] = herb_usage;
            }
            mpPage["金额"] = QString::asprintf("%.2f", costCount);
            mpPage["recipe_no"] = rec[count-1]["recipe_no"];
            mpPage["clinic_code"] = rec[count-1]["clinic_code"];
            mpPage["invoice_no"] = rec[count-1]["invoice_no"];

            printPage();
            pnt->end(); //循环完成，结束当前页面
            has_herb = false;

            break;
        }
    }
}

void Dialog_cfdy::printPage(QString recipe_type)
{

    if(recipe_type == "治疗处方")
    {
        //qDebug()<<"mpPage : "<<mpPage;
        mpPage.clear();
        mpPage = mp_page_undrug;
        //qDebug()<<"mpPage : "<<mpPage;
        //qDebug()<<"mp_page_undrug : "<<mp_page_undrug;
    }

    QString item, mode,print_item,font;
    QFont ft=QFont();
    double top,left,width,height,size;
    int position;
    qrm->prepare("select p_type,p_item,p_top,p_left,p_width,p_height,"
                 " p_font_name,p_font_size,p_position,p_mode,p_print_item,"
                 " p_item_type "
                 " from com_printer_setting "
                 " where p_type = '"  + recipe_type + "'");

    if(!qrm->exec())
    {
        QMessageBox::information(this,"错误","读取处方格式数据表失败：" + qrm->lastQuery());
        return;
    }

    bool special = false;   //处方标志，普通或精神

    while(qrm->next())
    {

        if(qrm->value("p_item_type").toString() == "item")
        {
            item = qrm->value(1).toString();
            top = qrm->value(2).toDouble();
            left = qrm->value(3).toDouble();
            width = qrm->value(4).toDouble();
            height = qrm->value(5).toDouble();
            font = qrm->value(6).toString();
            size = qrm->value(7).toDouble();
            position = qrm->value(8).toInt();
            mode = qrm->value(9).toString();
            print_item = qrm->value(10).toString();

            if(item == "处方标志")
            {
                item = mpPage.value(item);
                if(item != "普通")
                {
                    special = true;
                }
            }
            else
            {
                item = mpPage.value(item);
            }

            QString outText;    //输入文本
            if(mode == "1")
            {
                outText = print_item + "：" + item;
            }
            else if(mode == "0")
            {
                outText =  item;
            }
            else  if(mode == "3")
            {
                outText =  print_item ;
            }

            //QFontMetrics fm(font, prt);
            ft.setPixelSize(int(ptScale * size));
            ft.setFamily(font);
            QFontMetrics fm(ft, prt);
            int pixelsWide;

            if(item == "***以下空白***")
            {
                //行无内容，缩小字号
                size = size * 0.8;
                left = 50;
            }
            else
            {
                pixelsWide = fm.width(outText);
                if(pixelsWide > width * ptScale)
                {
                    //超过预定格式，缩小字号
                    size = size * ( width * ptScale / pixelsWide );//
                }
            }

            ft.setPixelSize(int(ptScale * size));
            ft.setFamily(font);
            pnt->setFont(ft);

            const QRect rect = QRect( left * ptScale, top * ptScale, width * ptScale, height * ptScale);
            QRect boundingRect;

            pnt->drawText(rect, position, outText, &boundingRect);

            if(recipe_type == "治疗处方")
            {

            }
            else
            {
                //药品处方
                if(print_item.mid(0,2) == "品名"){    //品名字串，后面附加价格

                    QString price = mpPage["price"+print_item.mid(2,1)];
                    if(!price.isEmpty()){//价格字串存在
                        QFontMetrics fm1(ft, prt);
                        int pixelsWide = fm1.width(outText);
                        ft.setPixelSize(int(ptScale * size * 0.8)); //缩小字号
                        pnt->setFont(ft);
                        //                       品名字串左起点    +  品名字串宽度   +  半个字符
                        const QRect rect = QRect( left * ptScale + pixelsWide + (ptScale * size * 0.8) /2 ,
                                                  ptScale *( top + size * 0.2) ,
                                                  width * ptScale, height * ptScale);
                        pnt->drawText(rect, position, "￥" + price , &boundingRect);
                    }
                }
            }

        }
        else if(qrm->value("p_item_type").toString() == "line")
        {
            mode = qrm->value(9).toString();
            top = qrm->value(2).toInt() * ptScale;
            left = qrm->value(3).toInt() * ptScale;
            width = qrm->value(4).toInt() * ptScale;
            height = qrm->value(5).toInt() * ptScale;

            QPen p ;
            if(mode == "1"){
                QVector<qreal> dash;
                dash << 0.2 * ptScale << 1 * ptScale;
                p.setStyle(Qt::DotLine);
                //p.setStyle(Qt::DashDotLine);
                //p.setStyle(Qt::CustomDashLine);
                p.setWidth(0.1 * ptScale);
                p.setDashPattern(dash);
                pnt->setPen(p);
            }else{
                p.setStyle(Qt::SolidLine);
                p.setWidth(0.2 * ptScale);
                pnt->setPen(p);
            }

            pnt->drawLine(left,top,height,width);
        }
        else if(qrm->value("p_item_type").toString() == "pic" && !special)
        {
            //非特殊处方直接打印签名
            item = mpPage.value(qrm->value(1).toString());

            top = qrm->value(2).toDouble();
            left = qrm->value(3).toDouble();
            width = qrm->value(4).toDouble();
            height = qrm->value(5).toDouble();
            const QRect rect = QRect( left * ptScale, top * ptScale, width * ptScale, height * ptScale);

            if(item.isEmpty())
            {
                continue;
            }

            QString tmp = "select sign_pic from com_empl_sign where empl_code = '" + item + "'";
            qDebug()<<"提取签名图像文件:"<<tmp<<"\n";
            qrmt->exec(tmp);

            if(qrmt->next())
            {
                QString pic64 = qrmt->value(0).toString();

                QByteArray image_data;
                QBuffer buffer(&image_data);
                buffer.open(QIODevice::WriteOnly);

                image_data = QByteArray::fromBase64(pic64.toLocal8Bit());

                QImage img = QImage::fromData(image_data, "PNG");

                pnt->drawImage(rect, img);

            }
            else
            {
                QMessageBox::information(this,"注意","签名信息 " + item + " 不存在！");
            }

            /*

            QFile f;
            QString fileName = "pics/" + item + ".png";

            if(f.exists(fileName) ){ //医师签字文件存在

                QPixmap pix;
                //QImage pix;
                pix.load(fileName);
                //pnt->fillRect(rect, Qt::transparent);
                pnt->drawImage(rect, pix.toImage());
            }else{
                QMessageBox::information(this,"注意","签名文件 " + fileName + " 不存在！");
            }
            */
        }
        else if(qrm->value("p_item_type").toString() == "barcode" )
        {
            //处方号条码
            item = mpPage.value("recipe_no");

            QFile f;
            QString fileName = pub::base_path + "/out.png";
            if(f.exists(fileName))
            {
                f.remove(fileName);
            }

            QStringList bar_arg;
            bar_arg << "-b" << "25" << "-d" << item;

            if(!zint_proc->startDetached("zint", bar_arg))
            {
                QMessageBox::information(this,"注意","生成处方号条码文件失败！");
            }
            else
            {
                top = qrm->value(2).toDouble();
                left = qrm->value(3).toDouble();
                width = qrm->value(4).toDouble();
                height = qrm->value(5).toDouble();
                const QRect rect = QRect( left * ptScale, top * ptScale, width * ptScale, height * ptScale);
                QFile f;
                //QString fileName = "out.png";

                QThread::msleep(150);

                if(f.exists(fileName) )
                {
                    //文件已经生成
                    QPixmap pix;
                    pix.load(fileName);
                    pnt->drawImage(rect, pix.toImage());
                }
                else
                {
                    QThread::msleep(150);
                    if(f.exists(fileName) ){ //文件存在
                        QPixmap pix;
                        pix.load(fileName);
                        pnt->drawImage(rect, pix.toImage());
                    }
                    else
                    {
                        QMessageBox::information(this,"注意","处方号条码文件不存在！");
                    }
                }
            }
        }
    }
}

void Dialog_cfdy::savePrintStatus(QString reci_no)
{
    //设置处方已打印标志
    QString str = "update sun_recipe_pr set print_flag = '1' where recipe_no= '" + reci_no + "'" ;
    qDebug() << "设置处方已打印标志: " << str<<"\n";
    qro->exec(str);

}

void Dialog_cfdy::onTimerOut()
{
    if(ui->lb_status->text() == "◇◆")
    {
        ui->lb_status->setText("◆◇");
    }
    else
    {
        ui->lb_status->setText("◇◆");
    }

    if(timerCount++ > 10)
    {
        //到达查询时间

        tm->stop();//暂停定时器
        qro->exec("select distinct invoice_no from sun_recipe_pr where "
                  " oper_date > trunc(sysdate) - 5 and drug_dept_code='"
                  + deptCode + "' and trans_type = '1' and print_flag = '0' ");

        QStringList invo;

        while(qro->next())
        {
            invo << qro->value(0).toString();
            qDebug()<<qro->value(0).toString();
        }

        QString invoice_no;
        foreach(invoice_no, invo)
        {
            if(!invoice_no.isEmpty())
            {
                ui->leSjh->setText(invoice_no);
                print_single_recipe();

            }
        }
        ui->leSjh->setText("");
        timerCount = 0;
        on_pbDisplay_clicked();    //显示已付药列表
        acceptListClicked = false;

        //非药品处方打印
        on_pb_undrug_print_clicked();


        if(!ui->ckb_jxc->isChecked())
        {
            //未勾先进销存上传
            tm->start(500);//恢复定时器
            return;
        }

        //进销存，库存变更查询
        if(stock_timer_count > 300) //300
        {
            stock_timer_count = 0;
            jxc->upload3501();//盘存
            jxc->upload0304("3503", "01", false);//入库
            jxc->upload0304("3504", "06", false);//退库
            qDebug()<<"进销存入库退库操作。";
        }

        stock_timer_count++;

        //进销存
        //if(stock_timer_count % 2 == 0) //30
        {
            //进销存处方查询
            qro->exec(" select distinct recipe_no, drug_dept_code "
                      " from  sun_recipe_pr  "
                      " where oper_date > trunc(sysdate) - 5 "
                      " and analyzed = '1' "
                      " and upload_flag = '0' ");
            QStringList reci;
            QString reci_list = "'recipe_no'";  //用于清除 upload 标志

            while(qro->next())
            {
                reci << qro->value(0).toString();
                reci_list += ",'" + qro->value(0).toString() + "'";
            }

            if(reci.size() > 0 )
            {
                qDebug()<<"进销存处方号："<<reci;
            }

            foreach(QString reci_no , reci)
            {
                if(!reci_no.isEmpty())
                {
                    jxc->upload0506("3505", "M1", reci_no);   //发药
                }
            }

            qro->exec(" select distinct OUT.recipe_no"
                      " from pha_com_output out"
                      " LEFT JOIN fin_opb_feedetail fee "
                      "      on FEE.RECIPE_NO = OUT.RECIPE_NO"
                      " left join sun_recipe_pr sun"
                      "      on sun.recipe_no = OUT.RECIPE_NO"
                      " where OUT.oper_date > trunc(sysdate) - 5"
                      " and OUT.out_type = 'M2' "
                      " and (out.upload_no = 0 or out.upload_no is null )"
                      " and FEE.CANCEL_FLAG = '0'"
                      " and sun.analyzed = '1'");

            reci.clear();

            while(qro->next())
            {
                reci << qro->value(0).toString();
            }

            if(reci.size() > 0)
            {
                qDebug()<<"进销存退药处方号："<<reci;
            }


            foreach(QString reci_no , reci)
            {
                if(!reci_no.isEmpty())
                {
                    jxc->upload0506("3506","M2", reci_no);   //退药
                }
            }

            //设置进销存已上传标志
            qro->exec(" update sun_recipe_pr set upload_flag = '1' "
                      " where recipe_no in(" + reci_list + ") ");

        }

        tm->start(500);//恢复定时器
    }
}

void Dialog_cfdy::on_pbDisplay_clicked()
{
    //显示已付药列表
    acceptListClicked = true;
    qro->prepare("select distinct invoice_no, card_no, name, opdt from ( "
                 "select  a.invoice_no, a.card_no, b.name, "
                 "to_char(a.oper_date,'yyyy-mm-dd hh24:mi:ss') opdt from "
                 "sun_recipe_pr a, fin_opr_register b "
                 "where trunc(a.oper_date) = trunc(sysdate) and "
                 "a.clinic_code = b.clinic_code) order by opdt desc");
    if(qro->exec())
    {
        ui->lwYfy->clear();
        while(qro->next())
        {
            QString t = qro->value(0).toString();
            t.append(" ");
            t.append(qro->value(3).toString());
            t.append(" ");
            t.append(qro->value(2).toString());
            ui->lwYfy->addItem(t);
        }
    }

}

void Dialog_cfdy::on_pbStop_clicked()
{

    tm->stop();
    //停止自动打印，允许手工打印
    ui->pbSinglePrint->setEnabled(true);
    ui->pbSearch->setEnabled(true);
    ui->pb_cancel_bill_search->setEnabled(true);
    ui->leSjh->setEnabled(true);
    ui->pbDisplay->setEnabled(true);
    ui->cbbCheck->setEnabled(true);
    ui->cbbDelivery->setEnabled(true);
    acceptListClicked = true;
}

void Dialog_cfdy::on_pbStart_clicked()
{

    druged_oper_code = send_oper_code = "";

    QString sq = "select empl_code from com_employee where empl_name = '"
            + ui->cbbCheck->currentText() + "'";
    qrm->exec(sq);
    qrm->next();
    druged_oper_code = qrm->value(0).toString();

    sq = "select empl_code from com_employee where empl_name = '"
            + ui->cbbDelivery->currentText() + "'";
    qrm->exec(sq);
    qrm->next();
    send_oper_code = qrm->value(0).toString();

    if(send_oper_code.isEmpty() || druged_oper_code.isEmpty())
    {
        QMessageBox::information(this,"注意","药师信息无效！");
        return;
    }

//    pub::send_oper_code = send_oper_code;
//    pub::druged_oper_code = druged_oper_code;

    //开始自动打印，禁止无关界面操作
    ui->lwYfy->clear();
    ui->pbSinglePrint->setEnabled(false);
    ui->pbTf->setEnabled(false);
    ui->pbTfzh->setEnabled(false);
    ui->pbBldy->setEnabled(false);
    ui->pb_bill_list_output->setEnabled(false);//费用清单
    ui->pbDisplay->setEnabled(false);
    ui->rbF->setChecked(true);
    ui->pbSearch->setEnabled(false);
    ui->pb_cancel_bill_search->setEnabled(false);
    acceptListClicked = false;
    ui->leSjh->setEnabled(false);
    ui->cbbCheck->setEnabled(false);
    ui->cbbDelivery->setEnabled(false);

    tm->start(500);

}

void Dialog_cfdy::processData(QString recipe_no)
{
    qDebug()<<"processData recipe_no is "<<recipe_no<<"\n";
    QList<QMap<QString,QString>> applyOutList;  //出库申请
    QList<QMap<QString,QString>> storageList;   //库存数据
    QMap<QString,QString> mp;
    //检索数据是否已经被处理
    qro->prepare("select recipe_no from pha_sto_recipe where  "
                 "RECIPE_STATE = '3' and recipe_no = :recipe_no");
    qro->bindValue(":recipe_no",recipe_no);

    if(!qro->exec())
    {
        QMessageBox::information(this,"error", qro->lastError().text());
        return;
    }
    if(qro->next())
    {
        qDebug()<<"recipe_no : "<< recipe_no << " , related data has been saved.";
        return; //已经做过数据处理
    }

    pub::db_o.transaction();
    QSqlQuery * qro_t1 = new QSqlQuery(pub::db_o);
    //QSqlQuery * qro_t2 = new QSqlQuery(pub::db_o);

    //update pha_sto_recipe 数据
    qro_t1->prepare("update pha_sto_recipe set RECIPE_STATE = '3', DRUGED_QTY = RECIPE_QTY, "
                 "DRUGED_DATE = sysdate, SEND_DATE = sysdate, EXT_FLAG1 = :ext_flag1,"
                 "SEND_OPER = :SEND_OPER, DRUGED_OPER = :DRUGED_OPER "
                 " where recipe_no = :recipe_no");
    qro_t1->bindValue(":ext_flag1", terminalCode);
    qro_t1->bindValue(":SEND_OPER", send_oper_code);
    qro_t1->bindValue(":DRUGED_OPER", druged_oper_code);
    qro_t1->bindValue(":recipe_no", recipe_no);
    //qro_t1->exec();

    if(!qro_t1->exec())
    {
        QMessageBox::information(this,"return error", qro_t1->lastError().text());
        delete qro_t1;
        pub::db_o.rollback();
        return;
    }


    //临时保存 PHA_COM_APPLYOUT

    qro_t1->prepare("SELECT * FROM PHA_COM_APPLYOUT WHERE "
                 " RECIPE_NO = :rcptn AND DRUG_DEPT_CODE = :dptcd AND CLASS3_MEANING_CODE = 'M1'"
                 " AND APPLY_STATE = '0' "
                 " order by comb_no,sequence_no");

    qro_t1->bindValue(":dptcd", deptCode);
    qro_t1->bindValue(":rcptn", recipe_no);
    if(!qro_t1->exec())
    {
        QMessageBox::information(this,"error", qro_t1->lastError().text());
        delete qro_t1;
        pub::db_o.rollback();
        return;
    }
    //
    while(qro_t1->next())
    {
        mp["APPLY_NUMBER"] = qro_t1->value("APPLY_NUMBER").toString();//申请流水号
        mp["DEPT_CODE"] = qro_t1->value("DEPT_CODE").toString();//申请部门编码（科室或者病区）
        mp["DRUG_DEPT_CODE"] = qro_t1->value("DRUG_DEPT_CODE").toString();//发药部门编码
        mp["CLASS3_MEANING_CODE"] = qro_t1->value("CLASS3_MEANING_CODE").toString();//出库申请分类
        mp["DRUG_CODE"] = qro_t1->value("DRUG_CODE").toString();//药品编码
        mp["TRADE_NAME"] = qro_t1->value("TRADE_NAME").toString();//药品商品名
        mp["DRUG_TYPE"] = qro_t1->value("DRUG_TYPE").toString();//药品类别
        mp["SPECS"] = qro_t1->value("SPECS").toString();//规格
        mp["PACK_UNIT"] = qro_t1->value("PACK_UNIT").toString();//包装单位
        mp["PACK_QTY"] = qro_t1->value("PACK_QTY").toString();//包装数
        mp["MIN_UNIT"] = qro_t1->value("MIN_UNIT").toString();//最小单位
        mp["RETAIL_PRICE"] = qro_t1->value("RETAIL_PRICE").toString();//零售价
        mp["APPLY_OPERCODE"] = qro_t1->value("APPLY_OPERCODE").toString();//申请人编码
        QDateTime dt = qro_t1->value("APPLY_DATE").toDateTime();
        mp["APPLY_DATE"] = dt.toString("yyyyMMddHHmmss");//申请日期
        mp["APPLY_STATE"] = qro_t1->value("APPLY_STATE").toString();//申请状态 0申请，1核准（出库），2作废，3暂不摆药
        mp["APPLY_NUM"] = qro_t1->value("APPLY_NUM").toString();//申请出库量(每付的总数量)
        mp["PATIENT_ID"] = qro_t1->value("PATIENT_ID").toString();//患者编号
        mp["PATIENT_DEPT"] = qro_t1->value("PATIENT_DEPT").toString();//患者科室
        mp["DRUGED_DEPT"] = qro_t1->value("DRUGED_DEPT").toString();//摆药科室
        mp["DRUGED_EMPL"] = qro_t1->value("DRUGED_EMPL").toString();//摆药人
        dt = qro_t1->value("DRUGED_DATE").toDateTime();
        mp["DRUGED_DATE"] = dt.toString("yyyyMMddHHmmss");//摆药日期
        mp["DOSE_ONCE"] = qro_t1->value("DOSE_ONCE").toString();//每次剂量
        mp["DOSE_UNIT"] = qro_t1->value("DOSE_UNIT").toString();//剂量单位
        mp["USAGE_CODE"] = qro_t1->value("USAGE_CODE").toString();//用法代码
        mp["USE_NAME"] = qro_t1->value("USE_NAME").toString();//用法名称
        mp["DFQ_FREQ"] = qro_t1->value("DFQ_FREQ").toString();//频次代码
        mp["DFQ_CEXP"] = qro_t1->value("DFQ_CEXP").toString();//频次名称
        mp["DOSE_MODEL_CODE"] = qro_t1->value("DOSE_MODEL_CODE").toString();//剂型编码
        mp["MO_ORDER"] = qro_t1->value("MO_ORDER").toString();//医嘱流水号
        mp["COMB_NO"] = qro_t1->value("COMB_NO").toString();//组合序号
        mp["RECIPE_NO"] = qro_t1->value("RECIPE_NO").toString();//处方号
        mp["SEQUENCE_NO"] = qro_t1->value("SEQUENCE_NO").toString();//处方内项目流水号
        mp["VALID_STATE"] = qro_t1->value("VALID_STATE").toString();//有效状态（0有效，1无效，2不摆药）
        applyOutList << mp;
        mp.clear();
    }
    qDebug()<<"applyOutList.length"<<applyOutList.length();

    //update PHA_COM_APPLYOUT
    qro_t1->prepare(" UPDATE PHA_COM_APPLYOUT"
                 " SET APPLY_STATE = '2', DRUGED_DEPT = DRUG_DEPT_CODE, DRUGED_EMPL = :empl,"
                 " DRUGED_DATE = sysdate, DRUGED_NUM = 0, OUT_BILL_CODE = '0' "
                 " WHERE DRUG_DEPT_CODE = :dept AND CLASS3_MEANING_CODE = 'M1' "
                 " AND RECIPE_NO = :rcn");
    qro_t1->bindValue(":dept", deptCode);
    qro_t1->bindValue(":empl", pub::usr_code);
    qro_t1->bindValue(":rcn", recipe_no);
    if(!qro_t1->exec())
    {
        QMessageBox::information(this,"Error in update pha_com_applyout", qro_t1->lastError().text());
        delete qro_t1;
        pub::db_o.rollback();
        return;
    }

    //INSERT pha_com_output
    foreach(mp, applyOutList)
    {
        //查询药品库存表PHA_COM_STORAGE，提取有效库存数据
        qro_t1->prepare("SELECT * FROM PHA_COM_STORAGE WHERE DRUG_DEPT_CODE = :dptcd "
                     " AND store_sum > 0 and DRUG_CODE = :drcd AND Valid_Flag = '1' "
                     //东软应用使用效期优先， 本应用使用group_code + batch_no。
                     " Order by to_number(group_code),VALID_DATE for update");
        qro_t1->bindValue(":dptcd", deptCode);
        qro_t1->bindValue(":drcd", mp["DRUG_CODE"]);
        if(!qro_t1->exec()){
            QMessageBox::information(this,"error", qro_t1->lastError().text());
            delete qro_t1;
            pub::db_o.rollback();
            return;
        }

        while(qro_t1->next())
        {
            QMap<QString, QString> m;
            m["DRUG_DEPT_CODE"] = qro_t1->value("DRUG_DEPT_CODE").toString();//库存科室 0-全部部门
            m["DRUG_CODE"] = qro_t1->value("DRUG_CODE").toString();//药品编码
            m["GROUP_CODE"] = qro_t1->value("GROUP_CODE").toString();//批次号
            m["BATCH_NO"] = qro_t1->value("BATCH_NO").toString();//批号
            m["TRADE_NAME"] = qro_t1->value("TRADE_NAME").toString();//药品商品名
            m["SPECS"] = qro_t1->value("SPECS").toString();//规格
            m["DRUG_TYPE"] = qro_t1->value("DRUG_TYPE").toString();//药品类别
            m["DRUG_QUALITY"] = qro_t1->value("DRUG_QUALITY").toString();//药品性质
            m["RETAIL_PRICE"] = qro_t1->value("RETAIL_PRICE").toString();//零售价
            m["WHOLESALE_PRICE"] = qro_t1->value("WHOLESALE_PRICE").toString();//批发价
            m["PURCHASE_PRICE"] = qro_t1->value("PURCHASE_PRICE").toString();//实进价
            m["PACK_UNIT"] = qro_t1->value("PACK_UNIT").toString();//包装单位
            m["PACK_QTY"] = qro_t1->value("PACK_QTY").toString();//包装数
            m["MIN_UNIT"] = qro_t1->value("MIN_UNIT").toString();//最小单位
            m["SHOW_FLAG"] = qro_t1->value("SHOW_FLAG").toString();//显示的单位标记
            QDateTime dt = qro_t1->value("VALID_DATE").toDateTime();
            m["VALID_DATE"] = dt.toString("yyyyMMddHHmmss");//有效期
            m["STORE_SUM"] = qro_t1->value("STORE_SUM").toString();//库存数量
            m["STORE_COST"] = qro_t1->value("STORE_COST").toString();//库存金额
            m["PREOUT_SUM"] = qro_t1->value("PREOUT_SUM").toString();//预扣库存数量
            m["PREOUT_COST"] = qro_t1->value("PREOUT_COST").toString();//预扣库存金额
            m["VALID_FLAG"] = qro_t1->value("VALID_FLAG").toString();//有效性标志 0 在用 1 停用 2 废弃
            m["PRODUCER_CODE"] = qro_t1->value("PRODUCER_CODE").toString();//生产厂家
            m["LAST_MONTH_NUM"] = qro_t1->value("LAST_MONTH_NUM").toString();//最近一次月结的库存量
            m["PLACE_CODE"] = qro_t1->value("PLACE_CODE").toString();//货位号
            m["STATE"] = qro_t1->value("STATE").toString();//在库状态（0-暂入库，1正式入库）
            m["MARK"] = qro_t1->value("MARK").toString();//备注
            m["OPER_CODE"] = qro_t1->value("OPER_CODE").toString();//操作员
            m["OPER_DATE"] = qro_t1->value("OPER_DATE").toString();//操作日期
            m["INVOICE_NO"] = qro_t1->value("INVOICE_NO").toString();//发票号
            m["ARK_FLAG"] = qro_t1->value("ARK_FLAG").toString();//'是否药柜管理药品 1 药柜管理 0 非药柜管理';
            m["ARK_QTY"] = qro_t1->value("ARK_QTY").toString();//药柜管理库存汇总数量
            m["manu_date"] = qro_t1->value("manu_date").toDate().toString("yyyy-MM-dd");//生产日期
            storageList << m;
        }

        //处理库存数据消耗
        QMap<QString,QString> sto;
        int aplNum = mp["APPLY_NUM"].toInt();   //申请出库数量
        int opNum;                              //本批次出库数量
        foreach(sto ,storageList)
        {
            int stoNum = sto["STORE_SUM"].toInt();  //本批次库存数量

            if(aplNum <= stoNum)
            {       //库存数量允许出库
                opNum = aplNum;     //出库数量 = 申请数量
            }
            else
            {                      //申请数量大于库存数量
                opNum = stoNum;     //出库数量 = 库存数量
            }
            qro_t1->exec("select SEQ_PHA_OUTBILL_ID.NEXTVAL from dual");
            qro_t1->next();
            QString OUT_BILL_CODE = qro_t1->value(0).toString();

            qro_t1->prepare("INSERT INTO pha_com_output (manu_date, DRUG_DEPT_CODE ,OUT_BILL_CODE ,SERIAL_CODE ,"
                         "GROUP_CODE , OUT_LIST_CODE ,OUT_TYPE ,CLASS3_MEANING_CODE ,IN_BILL_CODE ,"
                         "IN_SERIAL_CODE ,IN_LIST_CODE ,DRUG_CODE , TRADE_NAME ,DRUG_TYPE ,"
                         "DRUG_QUALITY ,SPECS ,PACK_UNIT ,PACK_QTY ,MIN_UNIT ,SHOW_FLAG , "
                         "SHOW_UNIT ,BATCH_NO , VALID_DATE , PRODUCER_CODE ,COMPANY_CODE ,"
                         "RETAIL_PRICE ,WHOLESALE_PRICE ,PURCHASE_PRICE , OUT_NUM ,SALE_COST ,"
                         "TRADE_COST ,APPROVE_COST ,STORE_NUM , STORE_COST ,SPECIAL_FLAG ,"
                         "OUT_STATE ,APPLY_NUM ,APPLY_OPERCODE ,APPLY_DATE ,EXAM_NUM ,EXAM_OPERCODE ,"
                         "EXAM_DATE ,APPROVE_OPERCODE ,APPROVE_DATE ,PLACE_CODE ,RETURN_NUM ,"
                         "DRUGED_BILL ,MED_ID ,DRUG_STORAGE_CODE , RECIPE_NO ,SEQUENCE_NO ,"
                         "GET_PERSON ,MARK ,OPER_CODE , OPER_DATE,ARK_FLAG,ARK_BILL_CODE,OUT_DATE"
                         ") VALUES ("
                         ":manu_date, :DRUG_DEPT_CODE ,:OUT_BILL_CODE ,1 ,:GROUP_CODE , '' ,'M1' ,'M1' ,0 ,0 ,'',"
                         ":DRUG_CODE , :TRADE_NAME ,:DRUG_TYPE ,:DRUG_QUALITY ,:SPECS ,:PACK_UNIT ,"
                         ":PACK_QTY ,:MIN_UNIT ,'0' , '' ,:BATCH_NO , :VALID_DATE ,:PRODUCER_CODE ,"
                         "(select  t.company_code from pha_com_input t where t.drug_dept_code = :DRUG_DEPT_CODE"
                         " and t.drug_code = :DRUG_CODE and t.group_code = :GROUP_CODE and rownum  = 1),"
                         ":RETAIL_PRICE ,0 ,:PURCHASE_PRICE , :OUT_NUM ,"
                         "(:OUT_NUM/:PACK_QTY)*:RETAIL_PRICE ,0 ,(:OUT_NUM/:PACK_QTY)*:PURCHASE_PRICE,"
                         ":STORE_NUM ,0 ,'0' ,'2' ,0 "
                         ",:APPLY_OPERCODE , SYSDATE ,:EXAM_NUM ,:EXAM_OPERCODE ,SYSDATE ,'' , SYSDATE ,"
                         "'' ,0 ,'0' ,'' ,:DRUG_STORAGE_CODE , :RECIPE_NO ,:SEQUENCE_NO ,:GET_PERSON ,"
                         "'' ,:OPER_CODE ,SYSDATE,'0',0,SYSDATE )");

            qro_t1->bindValue(":DRUG_DEPT_CODE", deptCode);//出库科室编码
            qro_t1->bindValue(":OUT_BILL_CODE",OUT_BILL_CODE);
            qro_t1->bindValue(":GROUP_CODE", sto["GROUP_CODE"]);//批次号
            QDateTime dt = QDateTime::fromString(sto["manu_date"], "yyyy-MM-dd");
            qro_t1->bindValue(":manu_date", dt);//生产日期
            qro_t1->bindValue(":DRUG_CODE", sto["DRUG_CODE"]);//药品编码
            qro_t1->bindValue(":TRADE_NAME", sto["TRADE_NAME"]);//药品商品名
            qro_t1->bindValue(":DRUG_TYPE", sto["DRUG_TYPE"]);//药品类别
            qro_t1->bindValue(":DRUG_QUALITY", sto["DRUG_QUALITY"]);//药品性质
            qro_t1->bindValue(":SPECS", sto["SPECS"]);//规格
            qro_t1->bindValue(":PACK_UNIT", sto["PACK_UNIT"]);//包装单位
            qro_t1->bindValue(":PACK_QTY", sto["PACK_QTY"]);//包装数
            qro_t1->bindValue(":MIN_UNIT", sto["MIN_UNIT"]);//最小单位
            qro_t1->bindValue(":BATCH_NO", sto["BATCH_NO"]);//批号
            dt = QDateTime::fromString(sto["VALID_DATE"],"yyyyMMddhhmmss");
            qro_t1->bindValue(":VALID_DATE", dt);//有效期
            qro_t1->bindValue(":PRODUCER_CODE", sto["PRODUCER_CODE"]);//生产厂家
            //qro_t1->bindValue(":COMPANY_CODE", sto["COMPANY_CODE"]);//供货单位代码
            qro_t1->bindValue(":RETAIL_PRICE", sto["RETAIL_PRICE"]);//零售价
            //qro_t1->bindValue(":WHOLESALE_PRICE", sto["WHOLESALE_PRICE"]);//批发价
            qro_t1->bindValue(":PURCHASE_PRICE", sto["PURCHASE_PRICE"]);//购入价
            qro_t1->bindValue(":OUT_NUM", opNum);//出库数量
            //qro_t1->bindValue(":SALE_COST","SALE_COST");//零售金额
            //qro_t1->bindValue(":APPROVE_COST",":APPROVE_COST");//购入金额
            qro_t1->bindValue(":STORE_NUM", stoNum - opNum);//出库后库存数量
            //qro_t1->bindValue(":STORE_COST",":STORE_COST");//出库后库存总金额
            qro_t1->bindValue(":APPLY_OPERCODE", mp["APPLY_OPERCODE"]);//申请出库人
            qro_t1->bindValue(":EXAM_NUM", opNum);//审批数量
            qro_t1->bindValue(":EXAM_OPERCODE", pub::usr_code);//审批人
            qro_t1->bindValue(":DRUG_STORAGE_CODE",mp["DEPT_CODE"]);//领药单位编码
            qro_t1->bindValue(":RECIPE_NO", mp["RECIPE_NO"]);//处方号
            qro_t1->bindValue(":SEQUENCE_NO", mp["SEQUENCE_NO"]);//处方流水号
            qro_t1->bindValue(":GET_PERSON",mp["PATIENT_ID"]);//领药人,  clinic_code
            qro_t1->bindValue(":OPER_CODE", pub::usr_code);//操作员
            if(!qro_t1->exec())
            {
                QMessageBox::information(this,"error", qro_t1->lastError().text());
                qDebug()<<"insert pha_com_output error."<<qro_t1->lastQuery();
                delete qro_t1;
                pub::db_o.rollback();
                return;
            }
            //核减库存
            qro_t1->prepare("UPDATE PHA_COM_STORAGE SET STORE_SUM = STORE_SUM - :out_num,"
                         "STORE_COST = STORE_COST - :out_num / pack_qty * RETAIL_PRICE, "
                         "BILL_CODE = :bill_code, SERIAL_CODE = 0, TARGET_DEPT = :target_dept, "
                         "CLASS2_CODE = '0320|M1', OPER_CODE   = :oper_code, OPER_DATE   = SYSDATE"
                         " WHERE  "
                         " DRUG_DEPT_CODE = :drug_dept_code "
                         " AND DRUG_CODE  = :drug_code"
                         " AND GROUP_CODE = :group_code "
                         " and batch_no = :batch_no");
            qro_t1->bindValue(":out_num", opNum);
            qro_t1->bindValue(":bill_code", OUT_BILL_CODE);
            qro_t1->bindValue(":target_dept" ,mp["DEPT_CODE"]);
            qro_t1->bindValue(":oper_code", pub::usr_code);
            qro_t1->bindValue(":drug_dept_code", deptCode);
            qro_t1->bindValue(":drug_code", sto["DRUG_CODE"]);
            qro_t1->bindValue(":group_code", sto["GROUP_CODE"]);
            qro_t1->bindValue(":batch_no", sto["BATCH_NO"]);

            if(!qro_t1->exec())
            {
                QMessageBox::information(this,"error", qro_t1->lastError().text());
                qDebug()<<"update pha_com_storage error."<<qro_t1->lastQuery();
                delete qro_t1;
                pub::db_o.rollback();
                return;
            }

            //update fin_opb_feedetail
            qro_t1->prepare("update fin_opb_feedetail set CONFIRM_FLAG = '1',"
                         " CONFIRM_CODE = :CONFIRM_CODE, CONFIRM_DEPT = :CONFIRM_DEPT, CONFIRM_DATE = sysdate, "
                         " NOBACK_NUM = 0, CONFIRM_NUM = QTY"
                         " where RECIPE_NO = :RECIPE_NO and MO_ORDER = :MO_ORDER and cancel_flag = '1'");
            qro_t1->bindValue(":CONFIRM_CODE", pub::usr_code);
            qro_t1->bindValue(":CONFIRM_DEPT", deptCode);
            qro_t1->bindValue(":RECIPE_NO", mp["RECIPE_NO"]);
            qro_t1->bindValue(":MO_ORDER", mp["MO_ORDER"]);
            if(!qro_t1->exec()){
                QMessageBox::information(this,"error", qro_t1->lastError().text());
                qDebug()<<"update fin_opb_feedetail error "<<qro_t1->lastError().text();
                qDebug()<<qro_t1->lastQuery();
                qDebug()<<pub::usr_code<<deptCode<<mp["RECIPE_NO"]<<mp["MO_ORDER"];
                delete qro_t1;
                pub::db_o.rollback();
                return;
            }

            aplNum = aplNum - opNum;    //申请数量 = 申请数量 - 已完成数量
            if(aplNum == 0){    //申请数量已经完成，退出循环
                break;
            }
        }
        storageList.clear();
    }
    delete qro_t1;
    //pub::db_o.rollback();
    pub::db_o.commit();
}

void Dialog_cfdy::on_lwYfy_clicked(const QModelIndex &index)
{
//    qDebug()<<index;
    if(!acceptListClicked)
    {
        //当前流程忽略单击
        return;
    }

    if(ui->rbF->isChecked() )
    {
        //发票检索状态
        ui->leSjh->setText(pub::getStr(ui->lwYfy->item(index.row())->text()," ",1));
    }
    else
    {
        //病志号检索
        clinicCode = pub::getStr(ui->lwYfy->item(index.row())->text()," ",4);
        ui->pbBldy->setEnabled(true);
        ui->pb_bill_list_output->setEnabled(true);//费用清单
        ui->pbSinglePrint->setEnabled(true);    //处方
    }

}

void Dialog_cfdy::on_lwYfy_doubleClicked(const QModelIndex &index)
{
    QString sq, txt, card_no, clinicCode, dt, rela_phone, patient_name;

    txt = pub::getStr(ui->lwYfy->item(index.row())->text()," ",1);

    if(txt.indexOf("-") < 0){   //字串不包含"-"，有可能是发票号

        bool o;
        int i = txt.mid(0,1).toInt( &o);

        Q_UNUSED(i)

        if(o){  //字串不包含"-"，首字符为数字，按发票方式检索
            sq = "select card_no, clinic_code from fin_opb_invoiceinfo where invoice_no = '" + txt + "'";
            qrot->exec(sq);
            qrot->next();
            card_no = qrot->value(0).toString();
            clinicCode = qrot->value(1).toString();

            sq = "select dept_name, rela_phone, name from fin_opr_register where clinic_code = '" + clinicCode + "'";
            qrot->exec(sq);
            qrot->next();
            deptName =  qrot->value(0).toString();
            rela_phone = qrot->value(1).toString();
            patient_name = qrot->value(2).toString();

        }else{
            //非数字，当前状态不可检索
            return;
        }

        dt = QDateTime::currentDateTime().toString("yyyy-MM-dd");    //此检索方式的日期为当日

    }else {
        bool o;
        int i = txt.mid(0,1).toInt( &o);
Q_UNUSED(i)
        if(o){  //转换成功，数字字串。当前状态为姓名或病志号检索
            clinicCode = pub::getStr(ui->lwYfy->item(index.row())->text()," ",4);
            sq = "select card_no, dept_name,rela_phone, name from fin_opr_register where clinic_code = '" + clinicCode + "'";
            qrot->exec(sq);
            qrot->next();
            card_no = qrot->value(0).toString();
            deptName =  qrot->value(1).toString();
            rela_phone =  qrot->value(2).toString();
            patient_name =  qrot->value(3).toString();
        }else{
            return;
        }

        dt = txt;   //指定的检索日期

    }

    sq="select r.hzzs,r.xbs,r.jws,r.tgjc,r.yz,r.ys ,r.atinc , 'l.xmmc', 'l.xmjg', 'p.lxdh' ,r.zd1,r.zd2,r.zd3"
       " from ys_bz_e_rec r "
       " where clinic_code = '" + clinicCode + "'";

    qrm->exec(sq);

    txt = "";

    bool hasDiag = true;
    bool hasRecipe = true;

    if(!qrm->next()){

        sq="select r.hzzs,r.xbs,r.jws,r.tgjc,r.yz,r.ys ,r.atinc , l.xmmc, l.xmjg, 'p.lxdh' ,r.zd1,r.zd2,r.zd3"
           " from ys_bz_e_rec r, ys_bz_e_main m, ys_bz_e_lib l, ys_bz_e_patient_info p"
           " where ";
        sq += " m.atinc = r.id and  r.rq='" + dt + "' ";
        sq += " and m.bzh='" + card_no + "'";
        sq += " and locate(r.zs , '" + deptName +"') > 0 ";  //ys_bz_e_rec表 诊室为简写，fin_opr_register表 诊室为完整名称
        sq += " and l.id=r.id ";
        sq += " and m.patient_id=p.atinc";
        if(!qrm->next())
        {

        hasDiag = false;
        }
//        QMessageBox::information(this,"注意","找不到关联的诊断信息！");
//        return;

    }

    {
        txt.append("患者姓名：" + patient_name + " , 联系电话：" +rela_phone + "\n\r\n\r");
        txt.append("病志号：" + card_no +  "     诊室名称：" + deptName + "\n\r");
        txt.append("主诉：" + qrm->value("hzzs").toString() + "\n\r");
        txt.append("现病史：" + qrm->value("xbs").toString() + "\n\r");
        txt.append("既往史：" + qrm->value("jws").toString() + "\n\r");
        txt.append("检查：" + qrm->value("tgjc").toString() + "\n\r");
        QString zd = qrm->value("zd1").toString();

        if(!qrm->value("zd2").toString().isEmpty()){
            zd.append(", " + qrm->value("zd2").toString());
        }
        if(!qrm->value("zd3").toString().isEmpty()){
            zd.append(", " + qrm->value("zd3").toString());
        }

        txt.append("医嘱：" + qrm->value("yz").toString() + "\n\r");

    }
    sq = "select item_name, specs, qty/pack_qty qqty , price_unit, qty/pack_qty * unit_price , cancel_flag, CONFIRM_CODE, "
         " doct_code , drug_flag "
         " from fin_opb_feedetail f where clinic_code ='"
         + clinicCode + "' and trans_type = '1' ";


    qrot->exec(sq);
    if(!qrot->next()){
        //QMessageBox::information(this,"注意","找不到关联的处方信息！");
        hasRecipe = false;
    }else{

        qrm->exec("select empl_name from com_employee where empl_code = '"
                  + qrot->value("doct_code").toString() + "'");
        qrm->next();
        doctName = qrm->value(0).toString();
        QString t_status, t_line, doct;
        while(true){
            t_status = "";
            if(qrot->value(5).toString() == "0"){
                t_status = "已退费";
            }
            if(qrot->value(8).toString() == "1" && qrot->value(6).toString().isEmpty()){
                t_status = "未付药";
            }

            t_line = doctName;
            t_line.append(" ");
            t_line.append(qrot->value(0).toString());
            t_line.append(" ");
            t_line.append(qrot->value(1).toString());
            t_line.append(" ");
            t_line.append(qrot->value(2).toString());
            t_line.append(" ");
            t_line.append(qrot->value(3).toString());
            t_line.append(" ");
            t_line.append(QString::asprintf("%.2f",qrot->value(4).toDouble())+"元");
            t_line.append(" " + t_status);
            txt.append("\n" + t_line);
            if(!qrot->next()){
                break;
            }
        }

    }
    if(hasDiag || hasRecipe){
        QMessageBox::information(this,"病志信息", txt);
    }else{
        QMessageBox::information(this,"注意","找不到关联的诊断和处方信息！");
    }

}

void Dialog_cfdy::on_leSjh_returnPressed()
{
    on_pbSearch_clicked();
}

void Dialog_cfdy::on_pbSearch_clicked()
{

    if(ui->leSjh->text().trimmed().isEmpty())
    {
        QMessageBox::information(this,"注意","请输入发票号、病志号或姓名！");
        return;
    }

    QString sq ;
    clinicCode = "";    //
    ui->pbTf->setEnabled(false);    //退费
    ui->pbTfzh->setEnabled(false);

    //检查当前处方状态是否已经退费
    if(ui->rbF->isChecked())
    {
        QString invo_no = pub::add0(ui->leSjh->text().trimmed(),12);

        sq = "SELECT distinct RECIPE_NO from fin_opb_feedetail where" // fee_code in('001','002','003')
             " invoice_no ='" + invo_no + "'";
        QString recipe_list = "'recipe'";
        qro->exec(sq);
        while(qro->next())
        {
            recipe_list += ",'" + qro->value(0).toString() + "'";
        }

        sq = "select RECIPE_NO, charge_flag FROM MET_NUI_CANCELITEM"
             " where recipe_no in (" + recipe_list + ") ";
        if(!qro->exec(sq)){
            QMessageBox::information(this,"error", "error at selec recipe_no from met_nui_cancelitem "+qro->lastError().text());
            return;
        }

        if(qro->next())
        {
            ui->pbTf->setText("退费单");
            ui->pbTf->setEnabled(true);     //可打印退费单
            if(qro->value(1).toString() == "0")
            {
                //收款处未做退费操作，可召回。如收款处已经退费，则无法进行召回
                ui->pbTfzh->setEnabled(true);
            }
        }
        else
        {
            ui->pbTf->setText("退费");
        }
    }

    ui->pbBldy->setEnabled(false);    //病历
    ui->pb_bill_list_output->setEnabled(false);//费用清单
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->lwYfy->clear();

    if(ui->rbF->isChecked())
    {
        //发票检索
        acceptListClicked = false;
        QString invo_no = pub::add0(ui->leSjh->text().trimmed(),12);
        qro->prepare("select item_name, specs, qty/pack_qty qqty , price_unit, "  //0-3
                     "qty/pack_qty * unit_price , cancel_flag, CONFIRM_CODE,clinic_code ,doct_code, fee_code "//4-9
                     " from fin_opb_feedetail f where invoice_no ='" + invo_no +
                     "'  and trans_type = '1' ");//and drug_flag = '1'

        if(!qro->exec())
        {
            qDebug()<<qro->lastError().text();
            qDebug()<<qro->lastQuery();
            qDebug()<<invo_no;
        }

        double count = 0;
        QString t;
        if(!qro->next()){
            QMessageBox::information(this,"错误","fin_opb_feedetail 找不到指定的发票号码！");
            return;
        }

        clinicCode = qro->value(7).toString();
        ui->pbBldy->setEnabled(true);//病历
        ui->pb_bill_list_output->setEnabled(true);//费用清单
        ui->pbSinglePrint->setEnabled(true);    //处方

        qrm->exec("select empl_name from com_employee where empl_code = '"
                  + qro->value("doct_code").toString() + "'");
        qrm->next();
        doctName = qrm->value(0).toString();
        //QMessageBox:: StandardButton result;

        while(true)
        {

            if(qro->value(6).toString().isEmpty()
//                    && qro->value(9).toString() != "005"
                    )
            {
                //无付药标志，非治疗处方
                //QMessageBox::information(this,"错误","此发票未付药！");
                return;
            }
            t = qro->value(8).toString();
            t.append(" ");
            t.append(qro->value(0).toString());
            t.append(" ");
            t.append(qro->value(1).toString());
            t.append(" ");
            t.append(qro->value(2).toString());
            t.append(" ");
            t.append(qro->value(3).toString());
            t.append(" ");
            t.append(QString::asprintf("%.2f",qro->value(4).toDouble())+"元");
            ui->lwYfy->addItem(t);
            count = count + qro->value(4).toDouble();
            if(!qro->next()){
                break;
            }
        }

        ui->lwYfy->addItem("合计金额: " + QString::asprintf("%.2f", count));

        ui->pbTf->setEnabled(true);//退费


        //ui->pb_bill_list_output->setEnabled(true);//费用清单
        //ui->pbSinglePrint->setEnabled(true);    //处方

        qrot->exec("select pact_name, oper_date, name from fin_opb_invoiceinfo where invoice_no = '" + invo_no + "'");
        qrot->next();

        patient_name = qrot->value(2).toString();

        if( qrot->value(0).toString() != "现金")
        {
            //非现金，有退费时限
            //QDateTime dt1 = qrot->value(1).toDateTime();
            //QDateTime dt2 = QDateTime::currentDateTime();
            //int ct = dt1.daysTo(dt2);
            QDate dt1 = qrot->value(1).toDate();
            QDate dt2 = QDate::currentDate();

            if( dt2.year() > dt1.year()
                    || dt2.month() > dt1.month() )
            {
                QMessageBox::information(this, "注意", "此发票为医保支付且已跨结算月份，请谨慎操作！");
            }
        }
    }
    else if(ui->rbB->isChecked())
    {
        //病志检索
        sq = "select to_char(reg_date,'yyyy-mm-dd hh24:mi:ss'), dept_name, clinic_code from fin_opr_register"
                     " where card_no = '" + pub::add0(ui->leSjh->text().trimmed(),10)+ "' order by reg_date";

    }
    else if(ui->rbX->isChecked())
    {
        //姓名检索
        sq = "select to_char(reg_date,'yyyy-mm-dd hh24:mi:ss'), dept_name, clinic_code from fin_opr_register"
                     " where name = '" + ui->leSjh->text().trimmed()+ "' order by reg_date";
    }

    if(ui->rbX->isChecked() || ui->rbB->isChecked())
    {
        if(!qro->exec(sq))
        {
            QMessageBox::information(this, "error", qro->lastError().text());
            qDebug()<< qro->lastError().text();
            qDebug()<<qro->lastQuery();
            return;
        }
        if(!qro->next())
        {
            QMessageBox::information(this, "注意", "找不到指定的病历号或患者姓名！");
            qDebug()<<qro->lastQuery();
            return;
        }
        QString t;
        while(true){
            t = qro->value(0).toString();
            t.append(" ");
            t.append(qro->value(1).toString());
            t.append(" ");
            t.append(qro->value(2).toString());

            ui->lwYfy->addItem(t);

            if(!qro->next()){
                break;
            }
        }
        acceptListClicked = true;  //
    }

}

void Dialog_cfdy::on_pbTf_clicked()
{

    QString invo_no = pub::add0(ui->leSjh->text().trimmed(),12);
    QString recipe = "'recipe'";
    QString sq;


    if(ui->pbTf->text() == "退费")
    {

        QString tip = "确定要对患者 " + patient_name + "， 发票号 "
                + ui->leSjh->text().trimmed() + " 的发票\n进行\"退费\"操作？";
        QMessageBox:: StandardButton result
                = QMessageBox::warning(NULL, "注意", tip, QMessageBox::Yes|QMessageBox::No);
        if(result != QMessageBox::Yes)
        {
            return;
        }

        pub::db_o.transaction();
        QSqlQuery * qro_t1 = new QSqlQuery(pub::db_o);
        QSqlQuery * qro_t2 = new QSqlQuery(pub::db_o);

        QString recipe_list = "'recipe_no'"; //处方号列表

        sq = "SELECT distinct RECIPE_NO from fin_opb_feedetail where invoice_no ='" + invo_no + "' ";
        qro_t1->exec(sq);
        while(qro_t1->next())
        {
            recipe_list += ",'" + qro_t1->value("RECIPE_NO").toString() + "'";
        }

        sq = "select INFO.TRADE_NAME, BREC.bar_code "
             " from pha_sto_barcode_rec brec"
             " LEFT JOIN PHA_COM_BASEINFO info on INFO.ID_CODE = brec.BAR_CODE_BASE"
             " where brec.valid_state = '1' and recipe_no in(" + recipe_list + ")";

        qDebug()<<"退费，检查追溯码："<<sq;
        qro_t1->exec(sq);
        QString barcode_list = "'barcode'";
        QString barcode_list_ret = "";
        while(qro_t1->next())
        {
            QString barcode = qro_t1->value(1).toString();
            if(barcode.length() == 20)
            {
                //追溯码
                //barcode_list += qro_t1->value(0).toString() + " : " +barcode + "\n";
                barcode_list += ",'" +barcode + "'";
            }
        }

        if(barcode_list != "'barcode'" ) //退费药品有追溯码
        {
            //获取退费药品追溯码
            barcode_return->prepare_display( barcode_list, recipe_list);
            barcode_return->set_value_saved(false);
            barcode_return->setModal(true);
            barcode_return->exec();

            QList<QMap<QString, QString>> ret_vals = barcode_return->return_values();

            QMap<QString, QString> mp;
            foreach(mp, ret_vals)
            {
                //保存退费追溯码
                sq = "insert into pha_sto_barcode_rec("
                     " rec_sn, " //等于 fin_opb_feedetail.mo_order 和 met_order_recipedetail.sequence_no';
                        "drug_code, "
                        "bar_code ,"    //处方中出现过的条码
                        "bar_code_base,"  //药品识别码。溯源码前7位，或制剂码，或商品码
                        "clinic_code," //clinic_code
                        "recipe_no,"    //处方号
                        "oper_date,"
                        "oper_code,"
                        "valid_state,"   //有效标志，1有效，非1无效
                        "bar_code_count"    //条码出现的次数
                        ") values(";
                sq += mp["rec_sn"] + ",";
                sq += "'" + mp["item_code"] + "',";    //
                sq += "'" + mp["bar_code"] + "',";    //处方中出现过的条码
                sq += "'" + mp["bar_code_base"] + "',";  //药品识别码。溯源码前7位，或制剂码，或商品码
                sq += "'" + mp["clinic_code"] + "',";   //clinic_code
                sq += "'" + mp["recipe_no"] + "',";      //处方号
                sq += "sysdate,";
                sq += "'" + pub::usr_code + "',";
                sq += "'0',";   //有效标志，1有效，非1无效
                sq += " 0 - " + mp["bar_code_ret_count"];      //条码出现的次数, 退费，负数
                sq += ")";

                qDebug()<<"保存退费追溯码:"<<sq;
                if(!qro_t1->exec(sq))
                {
                    QMessageBox::warning(this, "注意", "保存退费追溯码失败！");
                    delete qro_t1;
                    delete qro_t2;
                    pub::db_o.rollback();
                    return;
                }

                sq = " update pha_sto_barcode_rec "
                     " set valid_state = '0' "
                     " where bar_code = '%1'"
                     " and rec_sn = '%2'";
                sq = sq.arg(mp["bar_code"]).arg(mp["rec_sn"]);
                qDebug()<<"设置退费追溯码无效状态:"<<sq;
                qro_t1->exec(sq);

            }
        }

        //pha_sto_recipe
        sq = "update pha_sto_recipe set cancel_oper = '" + pub::usr_code + "', cancel_date = sysdate , valid_state = '2' "
             " where invoice_no = '" + invo_no + "' ";
        qDebug()<<"写入 pha_sto_recipe : "<<sq;
        if(!qro_t1->exec(sq))
        {
            QMessageBox::information(this,"error", "写入 pha_sto_recipe 发生错误！\n" + qro_t1->lastError().text());
            delete qro_t1;
            delete qro_t2;
            pub::db_o.rollback();
            return;
        }

        sq = "SELECT CLINIC_CODE, reg_dpcd DEPT_CODE ,ITEM_CODE ,ITEM_NAME ,SPECS ,"
             " unit_price  SALE_PRICE ,qty QUANTITY ,PRICE_UNIT ,EXEC_DPCD , OPER_CODE ,RECIPE_NO ,SEQUENCE_NO ,"
             "invoice_no BILL_NO , pack_qty QTY,card_NO  "
             "from fin_opb_feedetail where invoice_no ='" + invo_no + "' ";
        if(!qro_t1->exec(sq))
        {
            QMessageBox::information(this,"error", qro_t1->lastError().text());
            qDebug()<<qro_t1->lastQuery();
            qDebug()<<invo_no;
            delete qro_t1;
            delete qro_t2;
            pub::db_o.rollback();
            return;
        }
        qDebug()<<invo_no;

        while(qro_t1->next())
        {
            recipe.append(",'" +  qro_t1->value("RECIPE_NO").toString() + "'");

            qro_t2->prepare("INSERT INTO MET_NUI_CANCELITEM(oper_date,APPLY_NO,INPATIENT_NO ,BABY_FLAG ,DEPT_CODE ,"
                          "DRUG_FLAG ,ITEM_CODE ,ITEM_NAME ,SPECS ,SALE_PRICE ,QUANTITY , DAYS ,PRICE_UNIT ,"
                          "EXEC_DPCD ,OPER_CODE ,RECIPE_NO , SEQUENCE_NO ,BILL_NO ,CONFIRM_FLAG ,CHARGE_FLAG ,QTY,card_NO)"
                          " values"
                          " ( sysdate, SEQ_MET_NUI_CANCELITEM_ID.NEXTVAL ,:INPATIENT_NO , '0',:DEPT_CODE ,'1',"
                          ":ITEM_CODE ,:ITEM_NAME ,:SPECS , :SALE_PRICE ,:QUANTITY ,1,:PRICE_UNIT ,:EXEC_DPCD ,"
                          " :OPER_CODE ,:RECIPE_NO ,:SEQUENCE_NO ,:BILL_NO , '1','0',:QTY,:card_NO )"
                          );
            qro_t2->bindValue(":INPATIENT_NO", qro_t1->value("CLINIC_CODE").toString());
            qro_t2->bindValue(":DEPT_CODE", qro_t1->value("DEPT_CODE").toString());
            qro_t2->bindValue(":ITEM_CODE", qro_t1->value("ITEM_CODE").toString());
            qro_t2->bindValue(":ITEM_NAME", qro_t1->value("ITEM_NAME").toString());
            qro_t2->bindValue(":SPECS", qro_t1->value("SPECS").toString());
            qro_t2->bindValue(":SALE_PRICE", qro_t1->value("SALE_PRICE").toDouble());
            qro_t2->bindValue(":QUANTITY", qro_t1->value("QUANTITY").toInt());
            qro_t2->bindValue(":PRICE_UNIT", qro_t1->value("PRICE_UNIT").toString());
            qro_t2->bindValue(":EXEC_DPCD", qro_t1->value("EXEC_DPCD").toString());
            qro_t2->bindValue(":OPER_CODE", qro_t1->value("OPER_CODE").toString());
            qro_t2->bindValue(":RECIPE_NO", qro_t1->value("RECIPE_NO").toString());
            qro_t2->bindValue(":SEQUENCE_NO", qro_t1->value("SEQUENCE_NO").toString());
            qro_t2->bindValue(":BILL_NO", qro_t1->value("BILL_NO").toString());
            qro_t2->bindValue(":QTY", qro_t1->value("QTY").toInt());
            qro_t2->bindValue(":card_NO", qro_t1->value("card_NO").toString());
            if(!qro_t2->exec()){
                QMessageBox::information(this,"error", "error at insert met_nui_cancelitem "+qro_t2->lastError().text());
                qDebug()<<qro_t2->lastQuery();
                qDebug()<<qro_t1->value("CLINIC_CODE").toString();
                qDebug()<<qro_t1->value("DEPT_CODE").toString();
                qDebug()<<qro_t1->value("ITEM_CODE").toString();
                qDebug()<<qro_t1->value("ITEM_NAME").toString();
                qDebug()<<qro_t1->value("SPECS").toString();
                qDebug()<<qro_t1->value("SALE_PRICE").toDouble();
                qDebug()<<qro_t1->value("QUANTITY").toInt();
                qDebug()<<qro_t1->value("PRICE_UNIT").toString();
                qDebug()<<qro_t1->value("EXEC_DPCD").toString();
                qDebug()<<qro_t1->value("OPER_CODE").toString();
                qDebug()<<qro_t1->value("RECIPE_NO").toString();
                qDebug()<<qro_t1->value("SEQUENCE_NO").toString();
                qDebug()<<qro_t1->value("BILL_NO").toString();
                qDebug()<<qro_t1->value("QTY").toInt();
                qDebug()<<qro_t1->value("card_NO").toString();
                delete qro_t1;
                delete qro_t2;
                pub::db_o.rollback();
                return;
            }

        }
        qDebug()<<"MET_NUI_CANCELITEM";
        sq = "select drug_code,out_num,sale_cost,group_code,"
             " drug_storage_code,drug_dept_code, batch_no"
             " from pha_com_output where recipe_no in(" + recipe + ")";
        if(!qro_t1->exec(sq))
        {
            QMessageBox::information(this,"error", qro_t1->lastError().text());
            qDebug()<<qro_t1->lastQuery();
            qDebug()<<recipe;
            delete qro_t1;
            delete qro_t2;
            pub::db_o.rollback();
            return;
        }

        while(qro_t1->next())
        {
            qro_t2->prepare("UPDATE PHA_COM_STORAGE SET STORE_SUM = STORE_SUM + :qty, "
                          "STORE_COST = STORE_COST + :qty / pack_qty * retail_price, BILL_CODE = :invo_no, SERIAL_CODE = 1, "
                          "TARGET_DEPT = :tdept, CLASS2_CODE = '0320|M2', OPER_CODE = :oper, OPER_DATE   = SYSDATE  "
                          " WHERE "
                          " DRUG_DEPT_CODE = :ddept "
                          " AND DRUG_CODE  = :drug_code "
                          " AND GROUP_CODE = :grp "
                          " and batch_no = :batch_no");
            qro_t2->bindValue(":invo_no", invo_no);
            qro_t2->bindValue(":qty", qro_t1->value("out_num").toInt() );
            qro_t2->bindValue(":tdept", qro_t1->value("drug_storage_code").toString());
            qro_t2->bindValue(":ddept", qro_t1->value("drug_dept_code").toString());
            qro_t2->bindValue(":oper", pub::usr_code);
            qro_t2->bindValue(":drug_code", qro_t1->value("drug_code").toString());
            qro_t2->bindValue(":grp", qro_t1->value("group_code").toString());
            qro_t2->bindValue(":batch_no", qro_t1->value("batch_no").toString());

            if(!qro_t2->exec())
            {
                QMessageBox::information(this,"error", "error in UPDATE PHA_COM_STORAGE "+qro_t2->lastError().text());
                qDebug()<<qro_t2->lastQuery();
                qDebug()<< qro_t1->value("out_num").toInt() ;
                qDebug()<< qro_t1->value("drug_storage_code").toString();
                qDebug()<< qro_t1->value("drug_dept_code").toString();
                qDebug()<< pub::usr_code;
                qDebug()<< qro_t1->value("drug_code").toString();
                qDebug()<< qro_t1->value("group_code").toString();
                delete qro_t1;
                delete qro_t2;
                pub::db_o.rollback();
                return;
            }
        }
        qDebug()<<"pha_com_output";
        qro_t1->prepare("update fin_opb_feedetail set CONFIRM_FLAG = '1',CONFIRM_CODE = :oper,CONFIRM_DEPT = :dept,"
                     " CONFIRM_DATE = sysdate, NOBACK_NUM = qty,CONFIRM_NUM = 0 "
                     " where  invoice_no = :ivno");
        qro_t1->bindValue(":oper", pub::usr_code);
        qro_t1->bindValue(":dept", deptCode);
        qDebug()<<deptCode;
        qro_t1->bindValue(":ivno", invo_no);

        if(!qro_t1->exec()){
            QMessageBox::information(this,"error", "error in update fin_opb_feedetail "+qro_t1->lastError().text());
            qDebug()<<qro_t1->lastQuery();
            delete qro_t1;
            delete qro_t2;
            pub::db_o.rollback();
            return;
        }
        qDebug()<<"fin_opb_feedetail";
        sq = "UPDATE PHA_COM_OUTPUT SET RETURN_NUM = EXAM_NUM WHERE  RECIPE_NO in(" + recipe + ")";
        //qro_t1->bindValue(":rcp", recipe);
        if(!qro_t1->exec(sq)){
            QMessageBox::information(this,"error", "error in update pha_com_output "+qro_t1->lastError().text());
            qDebug()<<qro_t1->lastQuery();
            delete qro_t1;
            delete qro_t2;
            pub::db_o.rollback();
            return;
        }
        qDebug()<<qro_t1->lastQuery();
        qDebug()<<recipe;


        qDebug()<<"PHA_COM_OUTPUT";
        qro_t1->prepare("INSERT INTO pha_com_output ( manu_date,DRUG_DEPT_CODE,OUT_BILL_CODE,SERIAL_CODE,GROUP_CODE,OUT_LIST_CODE,"
                     "OUT_TYPE,CLASS3_MEANING_CODE,IN_BILL_CODE,IN_SERIAL_CODE,IN_LIST_CODE,DRUG_CODE,TRADE_NAME,"
                     "DRUG_TYPE,DRUG_QUALITY,SPECS,PACK_UNIT,PACK_QTY,MIN_UNIT,SHOW_FLAG,SHOW_UNIT,BATCH_NO,VALID_DATE,"
                     "PRODUCER_CODE,COMPANY_CODE,RETAIL_PRICE,WHOLESALE_PRICE,PURCHASE_PRICE,OUT_NUM,SALE_COST,TRADE_COST,"
                     "APPROVE_COST,STORE_NUM,STORE_COST,SPECIAL_FLAG,OUT_STATE,APPLY_NUM,APPLY_OPERCODE,APPLY_DATE,"
                     "EXAM_NUM,EXAM_OPERCODE,EXAM_DATE,APPROVE_OPERCODE,APPROVE_DATE,PLACE_CODE,RETURN_NUM,DRUGED_BILL,"
                     "MED_ID,DRUG_STORAGE_CODE,RECIPE_NO,SEQUENCE_NO,GET_PERSON,MARK,OPER_CODE,OPER_DATE,ARK_FLAG"
                     ",ARK_BILL_CODE,OUT_DATE) "
                     " select manu_date, DRUG_DEPT_CODE,SEQ_PHA_OUTBILL_ID.NEXTVAL,1,GROUP_CODE,OUT_LIST_CODE,'M2','M2',IN_BILL_CODE,"
                     "IN_SERIAL_CODE,IN_LIST_CODE,DRUG_CODE,TRADE_NAME,DRUG_TYPE,DRUG_QUALITY,SPECS,PACK_UNIT,PACK_QTY,"
                     "MIN_UNIT,SHOW_FLAG,SHOW_UNIT,BATCH_NO,VALID_DATE,PRODUCER_CODE,COMPANY_CODE,RETAIL_PRICE,"
                     "WHOLESALE_PRICE,PURCHASE_PRICE,0-OUT_NUM,0-SALE_COST,TRADE_COST,0-APPROVE_COST,0,0,SPECIAL_FLAG,"
                     "OUT_STATE,OUT_NUM,:OPER_CODE,sysdate,0-EXAM_NUM,EXAM_OPERCODE,sysdate,:OPER_CODE,sysdate,PLACE_CODE,"
                     "0,DRUGED_BILL,MED_ID,DRUG_STORAGE_CODE,RECIPE_NO,SEQUENCE_NO,GET_PERSON,MARK,:OPER_CODE,sysdate,"
                     "ARK_FLAG,ARK_BILL_CODE,sysdate from pha_com_output where RECIPE_NO in(" + recipe + ")");
        qro_t1->bindValue(":OPER_CODE", pub::usr_code);

        if(!qro_t1->exec()){
            QMessageBox::information(this,"error", "error in INTO pha_com_output "+qro_t1->lastError().text());
            qDebug()<<qro_t1->lastQuery();
            qDebug()<<pub::usr_code<<recipe;
            delete qro_t1;
            delete qro_t2;
            pub::db_o.rollback();
            return;
        }
        qDebug()<<"insertPHA_COM_OUTPUT";

        delete qro_t1;
        delete qro_t2;
        pub::db_o.commit();

        result= QMessageBox::warning(NULL, "注意", "退费完成，是否打印退费清单？",QMessageBox::Yes|QMessageBox::No);
        if(result == QMessageBox::Yes){

            tfPrint();
        }

    }
    else
    {
        //退费单补打
        tfPrint();
    }
    ui->pbTf->setEnabled(false);
    ui->pbTfzh->setEnabled(false);
    ui->pbBldy->setEnabled(false);    //病历
    ui->pb_bill_list_output->setEnabled(false);//费用清单
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->leSjh->clear();
}

void Dialog_cfdy::tfPrint()
{

//    QString fileName = pub::base_path;
//    fileName.append("/sheets/tui.xls");

//    QFile f(fileName);
//    if(!f.exists())
//    {
//        QMessageBox::information(this,"注意","退费单模板文件不存在！");
//        return;
//    }

//    QAxObject *excel;   //操作excel用于打印输出

//    excel = new QAxObject("Ket.Application"); //
//    qDebug()<<" 尝试启动 wps 电子表...\n";

//    if(excel->isNull())
//    {
//        excel = new QAxObject("Excel.Application"); //
//        qDebug()<<"  尝试启动 excel 电子表...\n";
//        if(excel->isNull())
//        {
//            QMessageBox::information(this,"错误","电子表启动失败！");
//            return;
//        }
//    }


//    excel->dynamicCall("SetVisible (bool Visible)", "false"); // 设置为不显示窗体
//    excel->setProperty("DisplayAlerts", false); //不显示任何警告信息

//    QAxObject *wkBooks = excel->querySubObject("Workbooks");
//    wkBooks->dynamicCall("Open(const QString&)", fileName);
//    QAxObject *book =  excel->querySubObject("ActiveWorkBook");
//    //QAxObject *book =  wkBooks->querySubObject("Open(const QString&)", fileName);
//    QAxObject *wkSheets = book->querySubObject("WorkSheets");
//    QAxObject *sheet = wkSheets->querySubObject("Item(int)", 1);
//    //QAxObject *cell  = new QAxObject ;
//    QAxObject *cell ;

//    //清空表格
//    int x,y;
//    for(x=6;x<11;x++)
//    {
//        for(y=2;y<5;y++)
//        {
//            cell = sheet->querySubObject("Cells(int, int)", x,  y);
//            cell->setProperty("Value", "");
//        }
//    }



    //收据号关联的退费项目
    QJsonObject jot;
    QJsonArray jsa_val;

    QString invo_no = pub::add0(ui->leSjh->text().trimmed(),12);
    QString sq ;

    sq = " select item_name trade_name , specs, price_unit pack_unit, "
         " qty / pack_qty qty, concat(concat( unit_price  ,'/'), price_unit) prs"
         " from fin_opb_feedetail"
         " where "
         " invoice_no = '%1' "
         " and qty >0 "
         " order by sequence_no ";
    sq = sq.arg(invo_no );

    qDebug()<<"收据号关联的退费项目 : "<<sq;
    qro->exec(sq);
    QString tmpit;
    int x, y;
    x=6;
    y=2;

    while(qro->next())
    {

        tmpit = qro->value("trade_name").toString();
        tmpit.append("("+qro->value("prs").toString()+")");
        //cell=sheet->querySubObject("Cells(int, int)",x,y);
        //cell->setProperty("Value",tmpit);

        jot.insert("val",tmpit);
        jot.insert("row", x);
        jot.insert("col", y);
        jsa_val << jot;
        y++;

        tmpit = qro->value("specs").toString();
        //cell = sheet->querySubObject("Cells(int, int)",x,y);
        //cell->setProperty("Value",tmpit);
        jot.insert("val",tmpit);
        jot.insert("row", x);
        jot.insert("col", y);
        jsa_val << jot;
        y++;

        tmpit=qro->value("qty").toString();
        tmpit = tmpit + qro->value("pack_unit").toString();
        //cell = sheet->querySubObject("Cells(int, int)",x,y);
        //cell->setProperty("Value",tmpit);
        jot.insert("val",tmpit);
        jot.insert("row", x);
        jot.insert("col", y);
        jsa_val << jot;

        x ++ ;
        y = 2;
    }

    //患者姓名、就诊日期
    sq = "select name,to_char(reg_date,'yyyy-mm-dd') "
         " from fin_opr_register "
         " where clinic_code = '"+ clinicCode +"'";

    qro->exec(sq);
    qro->next();
    tmpit = "患者:" + qro->value(0).toString() + "    发票号:" + invo_no;
    tmpit.append("    挂号日期:" + qro->value(1).toString());
    //cell = sheet->querySubObject("Cells(int, int)", 3, 2);
    //cell->setProperty("Value",tmpit);

    jot.insert("val",tmpit);
    jot.insert("row", 3);
    jot.insert("col", 2);
    jsa_val << jot;


    tmpit = "退药日期:" + QDate::currentDate().toString("yyyy-MM-dd");
    //cell = sheet->querySubObject("Cells(int, int)",3,6);
    //cell->setProperty("Value",tmpit);

    jot.insert("val",tmpit);
    jot.insert("row", 3);
    jot.insert("col", 6);
    jsa_val << jot;



    //收费类别、金额
    qro->exec("select pact_name, own_cost, pay_cost from fin_opb_invoiceinfo "
              "where invoice_no = '" + invo_no + "'");
    qro->next();
    double yb,xj;   //医保金额，现金金额
    yb = qro->value("pay_cost").toDouble();
    xj = qro->value("own_cost").toDouble();
    tmpit = qro->value("pact_name").toString();

    if(tmpit == "现金")
    {
        tmpit = tmpit + "，支付金额：" + QString::asprintf("%.2f", xj);
    }
    else
    {
        tmpit = "医保，卡：" +  QString::asprintf("%.2f", yb);
        tmpit = tmpit + "，现金："+QString::asprintf("%.2f", xj);
    }

    //cell = sheet->querySubObject("Cells(int, int)",12,2);
    //cell->setProperty("Value",tmpit);
    jot.insert("val",tmpit);
    jot.insert("row", 12);
    jot.insert("col", 2);
    jsa_val << jot;


    tmpit = "医生签字：" + doctName;
    //cell = sheet->querySubObject("Cells(int, int)",12,3);
    //cell->setProperty("Value",tmpit);
    jot.insert("val",tmpit);
    jot.insert("row", 12);
    jot.insert("col", 3);
    jsa_val << jot;

    /*
    //book->dynamicCall("Save()");   //保存文件
    book->setProperty("ActivePrinter", cfPrinter);
    book->dynamicCall("PrintOut()");   //打印输出
    //book->dynamicCall("PrintOut()");   //打印输出
    excel->dynamicCall("Quit()"); // 关闭excel
    book->dynamicCall("Close(Boolean)", false);  // 关闭文件
    delete excel;
    */


    //jot = d.object();
    jot.insert("row1",6);
    jot.insert("row2",10);
    jot.insert("col1",2);
    jot.insert("col2",4);
    QJsonArray jsa_clr ;
    jsa_clr << jot;

    QJsonObject jo; //打印参数
    jo.insert("excel_model", "/sheets/tui.xls");
    jo.insert("cell_value", jsa_val);
    jo.insert("clear_range", jsa_clr);

    //qDebug()<<"jsa_val  : " <<jsa_val<<"\n";

    //jo.insert("grid_range", jsa_rng);
    jo.insert("process_mode", "p"); //s保存，p打印

    pub::printOutExcel(jo, 2); //打印2次

    //pub::printOutExcel(jo);

//    QMessageBox::information(this,"注意","打印输出完毕！");

}

void Dialog_cfdy::on_rbF_clicked()
{
    ui->leSjh->clear();
    ui->lwYfy->clear();
    ui->pbTf->setEnabled(false);
    ui->pbTfzh->setEnabled(false);
    ui->pbBldy->setEnabled(false);
    ui->pb_bill_list_output->setEnabled(false);//费用清单
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->leSjh->setFocus();
}

void Dialog_cfdy::on_rbB_clicked()
{
    ui->leSjh->clear();
    ui->lwYfy->clear();
    ui->pbTf->setEnabled(false);
    ui->pbTfzh->setEnabled(false);
    ui->pbBldy->setEnabled(false);
    ui->pb_bill_list_output->setEnabled(false);//费用清单
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->leSjh->setFocus();
}

void Dialog_cfdy::on_pbBldy_clicked()
{

    ui->pbBldy->setEnabled(false);
    ui->pb_bill_list_output->setEnabled(false);//费用清单
    ui->pbSinglePrint->setEnabled(false);    //处方
    qApp->processEvents();
    QMap<QString, QString> pageInfo;
    QString bzAtinc;

    if(clinicCode.isEmpty()){
        QMessageBox::information(this,"注意","clinicCode 为空，无法检索病历!");
        return;
    }
    QString sq;
    sq = "select name, sex_code, to_char(birthday,'yyyyMMdd') birth,"
         " to_char( reg_date,'yyyy-mm-dd')reg_dt, "
         " dept_name, mcard_no , card_no , ynfr,see_docd, com.zyfw"
         " from fin_opr_register reg"
         " left join com_doctor_compare com on reg.see_docd = com.empl_code "
         " where clinic_code = '" + clinicCode + "'";

    qDebug()<<"检索挂号基础信息：";
    qDebug()<<sq<<"\n";

    qro->exec(sq);
    qro->next();
    pageInfo["name"] = qro->value(0).toString();
    pageInfo["sex"] = qro->value(1).toString() == "M" ? "男" : "女";
    pageInfo["birth"] = qro->value(2).toString() ;
    pageInfo["regdt"] = qro->value(3).toString() ;
    pageInfo["dpnm"] = qro->value(4).toString() ;
    pageInfo["mcard_no"] = qro->value(5).toString() ;
    pageInfo["card_no"] = qro->value(6).toString() ;
    pageInfo["ynfr"] = qro->value("ynfr").toString() ;
    pageInfo["see_docd"] = qro->value("see_docd").toString() ;
    pageInfo["zyfw"] = qro->value("zyfw").toString() ;

    if(pageInfo["see_docd"].isEmpty())
    {
        QMessageBox::information(this, "注意", "此病志尚未接诊,无法打印！");
        return;
    }

    sq = " select med_rec_item from ys_bz_e_print_rule "
         " where doct_type = '" + pageInfo["zyfw"] + "' ";

    qDebug()<<"检索医师身份关联的病志项目：";
    qDebug()<<sq<<"\n";

    qrm->exec(sq);
    QStringList med_rec_items;

    while(qrm->next())
    {
        med_rec_items << qrm->value(0).toString();
    }

qDebug()<<med_rec_items;


    //检查化验
    sq="select xmmc, xmjg from ys_bz_e_lib where clinic_code = '" + clinicCode + "'";
    qrm->exec(sq);
    while(qrm->next())
    {
        QString item = qrm->value("xmmc").toString();
        QString result = qrm->value("xmjg").toString();

        //pageInfo["aux_check"] +="\n\r";
        pageInfo["aux_check"] += item + " : " + result;
    }

    sq="select * from ys_bz_e_rec where clinic_code = '" + clinicCode + "'";

    qrm->exec(sq);
    qrm->next();

    bzAtinc = qrm->value("atinc").toString();
    pageInfo["jzys"] = qrm->value("ys").toString();
    pageInfo["hzzs"] = qrm->value("hzzs").toString();   //主诉
    pageInfo["xbs"] = qrm->value("xbs").toString();     //现病史
    pageInfo["jws"] = qrm->value("jws").toString();     //既往史
    pageInfo["gms"] = qrm->value("gms").toString();     //过敏史

    pageInfo["grs"] = qrm->value("person_hist").toString();     //个人史
    pageInfo["jzs"] = qrm->value("family_hist").toString();     //家族史
qDebug()<<"grs : "<<pageInfo["grs"];
    if(pageInfo["sex"] == "女")
    {
        pageInfo["yjs"] = qrm->value("menstr_hist").toString();     //月经史
    }
    else
    {
        pageInfo["yjs"] = "";
    }

    pageInfo["zzms"] = qrm->value("tgjc").toString();   //体格检查
    pageInfo["zzms_tr"] = qrm->value("tgjc_tr").toString();   //中医查体
    pageInfo["zybz"] = qrm->value("zybz").toString();   //中医辩证
    pageInfo["zljh"] = qrm->value("medical_plan").toString();       //诊疗计划
    pageInfo["zylz"] = qrm->value("similar_syndrom").toString();       //中医类证鉴别
    pageInfo["zyzz"] = qrm->value("treat_tr").toString();       //中医治则
    pageInfo["yz"] = qrm->value("yz").toString();       //医嘱
    pageInfo["sm3"] = qrm->value("sm3").toString();

    QString zyzd,xyzd;  //中医诊断，西医诊断

    //QString zd = qrm->value("zd1").toString();
    if(!qrm->value("zyzd1").toString().isEmpty())
    {
        zyzd = qrm->value("zyzd1").toString() + "[" + qrm->value("zyzh1").toString() + "]";
    }

    if(!qrm->value("zyzd2").toString().isEmpty())
    {
        zyzd += " / " + qrm->value("zyzd2").toString() + "[" + qrm->value("zyzh2").toString() + "]";
    }

    if(!qrm->value("zyzd3").toString().isEmpty())
    {
        zyzd += " / " + qrm->value("zyzd3").toString() + "[" + qrm->value("zyzh3").toString() + "]";
    }

    xyzd = qrm->value("zd1").toString();    //西医诊断至少有一个

    if(!qrm->value("zd2").toString().isEmpty()){
        xyzd.append(" / " + qrm->value("zd2").toString());
    }

    if(!qrm->value("zd3").toString().isEmpty()){
        xyzd.append(" / " + qrm->value("zd3").toString());
    }

    pageInfo["zyzd"] = zyzd;
    pageInfo["xyzd"] = xyzd;



    QString item;

    QString fileName = pub::base_path;
    fileName.append("/sheets/bz_tmp.doc");

    QFile f(fileName);
    if(!f.exists())
    {
        QMessageBox::information(this,"注意","病志模板文件不存在！");
        return;
    }

    if(QFile::exists("c:/bz.doc"))
    {
        QFile::remove("c:/bz.doc");
    }

    f.copy("c:/bz.doc");

    //QFile::copy(fileName, "c:/bz.doc", true);

    fileName = "c:/bz.doc";

    QAxObject *m_WordFile = new QAxObject();

    bool bFlag = m_WordFile->setControl( "Kwps.Application" );// 尝试用wps打开

    if(NULL == m_WordFile)
    {

        bFlag = m_WordFile->setControl( "word.Application" );
        if(!bFlag)
        {
            QMessageBox::information(this,"错误","Office 文档系统启动失败！");
            return ;
        }
    }

    m_WordFile->setProperty("Visible", false);
    //m_WordFile->setProperty("Visible", true);
    // 获取所有的工作文档
    QAxObject *Documents = m_WordFile->querySubObject("Documents");
    if(NULL == Documents)
    {
        QMessageBox::information(this,"错误","Can't retreive Documents！");
        return ;
    }
    // 新建一个文档
    QAxObject* document = Documents->querySubObject("Open(const QString&)", fileName );

    // 获取当前激活的文档
    QAxObject *m_Document = m_WordFile->querySubObject("ActiveDocument");
    //QAxObject *my_tst = m_Document->querySubObject("pagesetup");
    QAxObject *word_select = m_WordFile->querySubObject("Selection");


    word_select->querySubObject("Font")->setProperty("Size", 18);
    word_select->querySubObject("Font")->setProperty("Name", "黑体");
    word_select->querySubObject("ParagraphFormat")->setProperty("Alignment", 1);

    if(pageInfo["ynfr"] == "1")
    {
        item="门诊病历(初诊)\n";
    }
    else
    {
        item="门诊病历(复诊)\n";
    }

    word_select->dynamicCall("TypeText(const string)", item);

    word_select->querySubObject("Font")->setProperty("Size", 12);
    word_select->querySubObject("ParagraphFormat")->setProperty("Alignment", 0);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "姓名：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["name"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t性别：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["sex"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t年龄：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    QStringList ageList = pub::getNl(pageInfo["birth"]);
    word_select->dynamicCall("TypeText(const string)", ageList[0]+ageList[1]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t病志号：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["card_no"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\n挂号日期：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["regdt"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t诊室：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["dpnm"]);

    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t医保卡号：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["mcard_no"]);


    word_select->dynamicCall("TypeText(const string)", "\n");

    QAxObject* paragraph = word_select->querySubObject("ParagraphFormat");
    paragraph->setProperty("Alignment", "wdAlignParagraphCenter");

    item="- - - - - - - - - - - - - - - - - - - - "
         "- - - - - - - - - - - - - - - - - - - -";

    word_select->dynamicCall("TypeText(const string)", item);

    paragraph->setProperty("Alignment", "wdAlignParagraphLeft");
    //item = item+"\n";

    if(med_rec_items.indexOf("患者主诉") > -1  && !pageInfo["hzzs"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【患者主诉】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["hzzs"]);
    }

    if(med_rec_items.indexOf("现病史") > -1  && !pageInfo["xbs"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【现病史】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["xbs"]);
    }

    if(med_rec_items.indexOf("既往史") > -1  && !pageInfo["jws"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【既往史】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["jws"]);
    }

    if(med_rec_items.indexOf("过敏史") > -1  && !pageInfo["gms"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【过敏史】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["gms"]);
    }

    if(med_rec_items.indexOf("个人史") > -1  && !pageInfo["grs"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【个人史】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["grs"]);
    }

    if(med_rec_items.indexOf("月经史") > -1 && !pageInfo["yjs"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【月经史】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["yjs"]);
    }

    if(med_rec_items.indexOf("家族史") > -1  && !pageInfo["jzs"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【家族史】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["jzs"]);
    }

    if(med_rec_items.indexOf("中医查体") > -1 && !pageInfo["zzms_tr"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【中医查体】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["zzms_tr"]);
    }

    if(med_rec_items.indexOf("体格检查") > -1)
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【体格检查】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["zzms"]);
    }

    if(med_rec_items.indexOf("辅助检查") > -1 && !pageInfo["aux_check"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【辅助检查】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["aux_check"]);

    }

    if(med_rec_items.indexOf("辨证依据") > -1 && !pageInfo["zybz"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【辨证依据】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["zybz"]);
    }

    if(med_rec_items.indexOf("中医类证鉴别") > -1 && !pageInfo["zylz"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【中医类证鉴别】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["zylz"]);
    }

    if(med_rec_items.indexOf("中医诊断") > -1 && !pageInfo["zyzd"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【中医诊断】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["zyzd"]);
    }

    if(med_rec_items.indexOf("西医诊断") > -1)
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【西医诊断】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["xyzd"]);
    }

    if(med_rec_items.indexOf("中医治则") > -1 && !pageInfo["zyzz"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【中医治则】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["zyzz"]);
    }

    if(med_rec_items.indexOf("诊疗计划") > -1 && !pageInfo["zljh"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【诊疗计划】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["zljh"]);
    }

    if(med_rec_items.indexOf("医嘱") > -1  && !pageInfo["yz"].isEmpty())
    {
        word_select->querySubObject("Font")->setProperty("Name", "宋体");
        word_select->dynamicCall("TypeText(const string)", "\n【医嘱】\n");
        word_select->querySubObject("Font")->setProperty("Name", "楷体");
        word_select->dynamicCall("TypeText(const string)", pageInfo["yz"]);
    }

    word_select->dynamicCall("TypeText(const string)", "\n");

    word_select->dynamicCall("TypeText(const string)", "\n");
    word_select->querySubObject("Font")->setProperty("Name", "宋体");
    word_select->dynamicCall("TypeText(const string)", "\t\t\t\t\t\t\t\t\t主治医生（签字或盖章）：");
    word_select->querySubObject("Font")->setProperty("Name", "楷体");
    word_select->dynamicCall("TypeText(const string)", pageInfo["jzys"]);


    m_Document->querySubObject("ActiveWindow")->querySubObject("ActivePane")
            ->querySubObject("View")->setProperty("SeekView", 9 );//显示页眉 wdSeekCurrentPageHeader

    if(pageInfo["sm3"].isEmpty() )
    {
        qDebug()<<"item has no sm3 info.\n";
    }
    else
    {
        QFile f;
        QString fileName = pub::base_path + "/out.png";
        if(f.exists(fileName))
        {
            qDebug()<<"remove picture file " + pub::base_path + "/out.png exists.\n";
            if(f.remove(fileName))
            {
                qDebug()<<"old file removed.\n";
            }
            else
            {
                qDebug()<<"remove old file failure.\n";
            }
        }
        else
        {
            qDebug()<<" picture file " + pub::base_path + "/out.png not exists.\n";
        }


        //生成病志二维码图片文件
        QStringList bar_arg;
        bar_arg << "-b" << "58" << "-d" << pageInfo["sm3"];

        if(!zint_proc->startDetached("zint", bar_arg))
        {
            QMessageBox::information(this,"注意","生成病志二维码文件失败！");
        }
        else
        {
            //检查图片文件是否已经生成
            qDebug()<<"will sleep 150ms wait picture file .\n";
            QThread::msleep(150);
            if(!f.exists(fileName))
            {
                qDebug()<<"wait for QR create, sleep another 150ms.\n";
                QThread::msleep(150);
                if(!f.exists(fileName) )
                {
                    QMessageBox::information(this,"注意","二维码图片文件不存在！");
                }
                else
                {
                    qDebug()<<"new pic file has been generated in second 150ms.\n";
                }
            }
            else
            {
                qDebug()<<"new pic file has been generated in first 150ms.\n";
            }

            //插入图片
            //QString imagePath = pub::base_path + "/out.png"; // 替换为实际路径

            word_select = m_WordFile->querySubObject("Selection");

            QAxObject* inlineShapes = word_select->querySubObject("InlineShapes");
            QAxObject* inlineShape = inlineShapes->querySubObject("AddPicture(const QString&)",
                                                                  QDir::toNativeSeparators(fileName));//imagePath


            if (inlineShape && !inlineShape->isNull()) {
                // 转换为Shape对象
                QAxObject* shape = inlineShape->querySubObject("ConvertToShape()");
                if (shape && !shape->isNull()) {
                    // 设置浮于文字上方
                    //shape->setProperty("WrapFormat.Type", 4); // wdWrapNone = 4

                    shape->setProperty("WrapFormat.Type", 1); // wdWrapNone = 4

                    // 设置位置
                    shape->setProperty("Left", 10);
                    shape->setProperty("Top", 10);

                    delete shape;
                }
                delete inlineShape;
            }


        }
    }

    word_select->dynamicCall("TypeText(const string)", pub::hos_name);

    //wdAlignParagraphRight:右边对齐;
    //wdAlignParagraphJustify:两边对齐;
    //wdAlignParagraphLeft:左边对齐;
    //wdAlignParagraphCenter:中间对齐;

    /*
    wdSeekCurrentPageFooter 	10 	当前页页脚。
    wdSeekCurrentPageHeader 	9 	当前页页眉。
    wdSeekEndnotes 	8 	尾注。
    wdSeekEvenPagesFooter 	6 	偶数页页脚。
    wdSeekEvenPagesHeader 	3 	偶数页页眉。
    wdSeekFirstPageFooter 	5 	首页页脚。
    wdSeekFirstPageHeader 	2 	首页页眉。
    wdSeekFootnotes 	7 	脚注。
    wdSeekMainDocument 	0 	主文档。
    wdSeekPrimaryFooter 	4 	主页脚。
    wdSeekPrimaryHeader 	1 	主页眉。
    */



    m_Document->querySubObject("ActiveWindow")->querySubObject("ActivePane")
            ->querySubObject("View")->setProperty("SeekView",10 );//显示页脚wdSeekCurrentPageFooter

    item="打印时间：";
    QDateTime c;
    QString print_times;
    if(!bzAtinc.isEmpty()){

        qrm->exec("update ys_bz_e_rec set dybz = dybz + 1 where atinc = " + bzAtinc);
        qrm->exec("select dybz from ys_bz_e_rec where atinc = " + bzAtinc);
        qrm->next();

        print_times = qrm->value(0).toString();
        item=item + c.currentDateTime().toString("yyyy/MM/dd hh:mm:ss");
        item=item+"\t 第 " + print_times + " 次打印";
    }
    else
    {
        item = item + c.currentDateTime().toString("yyyy/MM/dd hh:mm:ss");
        item = item + "\t *数据过渡期间记录不完整*";//+DateTimePicker2->Date.DateString()+"        ";

    }
    sq = "insert into ys_bz_e_rec_print_rec "
         "(clinic_code, sm3, print_time , times_count, "
         " print_ip, print_mac, print_oper)"
         "values"
         "('%1', '%2', now(), %3, '%4', '%5', '%6')";
    sq = sq.arg(clinicCode)
            .arg(pageInfo["sm3"])
            .arg(print_times)
            .arg(pub::localIP)
            .arg(pub::localMac)
            .arg(pub::usr_code);
    qDebug()<<"保存打印记录：\n";
    qrm->exec(sq);

    //item=item+"\t 此病历经医生签字后生效";
    word_select->dynamicCall("TypeText(const string)", item);



    m_Document->dynamicCall("SaveAs (const QString&)", fileName);

    qDebug()<<"SaveAs (const QString&)\n";


    m_WordFile->setProperty("ActivePrinter", bzPrinter);
    m_Document->dynamicCall("PrintOut()");
qDebug()<<"PrintOut()\n";
    m_Document->dynamicCall("Close (boolean)", true);  //关闭文本窗口
    m_WordFile->dynamicCall("Quit(void)");  //退出word

}

void Dialog_cfdy::on_rbX_clicked()
{
    ui->leSjh->clear();
    ui->lwYfy->clear();
    ui->pbTf->setEnabled(false);
    ui->pbTfzh->setEnabled(false);
    ui->pbBldy->setEnabled(false);
    ui->pb_bill_list_output->setEnabled(false);//费用清单
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->leSjh->setFocus();
}

void Dialog_cfdy::on_pbTfzh_clicked()
{

    QString invo_no = pub::add0(ui->leSjh->text().trimmed(),12);
    QString recipe = "'recipe'";
    QString sq;

    QString tip = "确定要对发票号 " + ui->leSjh->text().trimmed() + " 进行\"退费召回\"操作？";
    QMessageBox:: StandardButton result= QMessageBox::warning(NULL, "注意", tip, QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No)
    {
        return;
    }

    pub::db_o.transaction();
    QSqlQuery * qro_t1 = new QSqlQuery(pub::db_o);
    QSqlQuery * qro_t2 = new QSqlQuery(pub::db_o);

    //删除退费中间表
    sq = "delete from MET_NUI_CANCELITEM where bill_no = '" + invo_no + "'";
    qDebug()<<"删除退费中间表:"<<sq<<"\n";
    qro_t1->exec(sq);

    //提取处方号
    sq = "SELECT distinct RECIPE_NO from fin_opb_feedetail where invoice_no ='" + invo_no + "' ";
    qDebug()<<"提取处方号:"<<sq<<"\n";
    if(!qro_t1->exec(sq))
    {
        QMessageBox::information(this,"error", "提取处方号失败！");
        qDebug()<< qro_t1->lastError().text();
        delete qro_t1;
        delete qro_t2;
        pub::db_o.rollback();
        return;
    }

    while(qro_t1->next())
    {
        recipe.append(",'" +  qro_t1->value(0).toString() + "'");
    }

    //设置退费时扫入的条码数据无效
    sq = "update pha_sto_barcode_rec set valid_state = '0' "
         " where RECIPE_NO in(" + recipe + ") and bar_code_count < 0 ";
    qDebug()<<"处理退费召回的条码数据(pha_sto_barcode_rec, bar_code_count < 0)："<<sq<<"\n";
    if(!qro_t1->exec(sq))
    {
        QMessageBox::information(this,"error", "error in process pha_sto_barcode_rec(bar_code_count < 0 )");
        delete qro_t1;
        delete qro_t2;
        pub::db_o.rollback();
        return;
    }

    sq = "update pha_sto_barcode_rec set valid_state = '1' "
         " where RECIPE_NO in(" + recipe + ") and bar_code_count > 0 ";
    qDebug()<<"处理退费召回的条码数据(pha_sto_barcode_rec, bar_code_count > 0)："<<sq<<"\n";
    if(!qro_t1->exec(sq))
    {
        QMessageBox::information(this,"error", "error in process pha_sto_barcode_rec（bar_code_count > 0)");
        delete qro_t1;
        delete qro_t2;
        pub::db_o.rollback();
        return;
    }

    //设置退费时扫入的条码数据无效
    sq = "update pha_sto_barcode_return set valid_status = '0' "
         " where RECIPE_NO in(" + recipe + ") ";
    qDebug()<<"处理退费召回的条码数据(pha_sto_barcode_return)："<<sq<<"\n";
    if(!qro_t1->exec(sq))
    {
        QMessageBox::information(this,"error", "error in pha_sto_barcode_return ");
        delete qro_t1;
        delete qro_t2;
        pub::db_o.rollback();
        return;
    }


    //整理药品消耗数据
    sq = "UPDATE PHA_COM_OUTPUT SET RETURN_NUM = 0 WHERE  RECIPE_NO in(" + recipe + ")";
    qDebug()<<"整理药品消耗数据："<<sq<<"\n";

    if(!qro_t1->exec(sq))
    {
        QMessageBox::information(this,"error", "error in update pha_com_output ");
        qDebug()<<qro_t1->lastError().text();

            delete qro_t1;
            delete qro_t2;
            pub::db_o.rollback();
            return;

    }

    sq = "delete from PHA_COM_OUTPUT  WHERE OUT_NUM < 0 and RECIPE_NO in(" + recipe + ")";
    qDebug()<<"删除插入的负数药品消耗数据："<<sq<<"\n";

    if(!qro_t1->exec(sq))
    {
        QMessageBox::information(this,"error", "error in update pha_com_output ");
        qDebug()<<qro_t1->lastError().text();

            delete qro_t1;
            delete qro_t2;
            pub::db_o.rollback();
            return;

    }

    sq = "select * from pha_com_output where recipe_no in(" + recipe + ")";
    qDebug()<<"提取处方号相关药品数据："<<sq<<"\n";

    if(!qro_t2->exec(sq))
    {
        QMessageBox::information(this,"error", "提取处方号相关药品数据错误！");
        qDebug()<<qro_t2->lastQuery();
        delete qro_t1;
        delete qro_t2;
        pub::db_o.rollback();
        return;
    }

    while(qro_t2->next())
    {
        //查询药品库存表PHA_COM_STORAGE，提取有效库存数据
        sq = "SELECT * FROM PHA_COM_STORAGE WHERE DRUG_DEPT_CODE = '%1' "
             " and store_sum > 0 and DRUG_CODE = '%2' AND Valid_Flag = '1' "
             " order by to_number(group_code),VALID_DATE for update";
        sq = sq.arg(qro_t2->value("drug_dept_code").toString())
                .arg(qro_t2->value("drug_code").toString());
        qDebug()<<"查询 PHA_COM_STORAGE 提取有效库存数:"<<sq<<"\n";

        if(!qro_t1->exec(sq))
        {
            QMessageBox::information(this,"error", qro_t1->lastError().text());
            delete qro_t1;
            delete qro_t2;
            pub::db_o.rollback();
            return;
        }

        QList<QMap<QString,QString>> storageList;   //库存数据

        while(qro_t1->next())
        {
            QMap<QString, QString> m;
            m["DRUG_DEPT_CODE"] = qro_t1->value("DRUG_DEPT_CODE").toString();//库存科室 0-全部部门
            m["DRUG_CODE"] = qro_t1->value("DRUG_CODE").toString();//药品编码
            m["GROUP_CODE"] = qro_t1->value("GROUP_CODE").toString();//批次号
            m["BATCH_NO"] = qro_t1->value("BATCH_NO").toString();//批号
            m["TRADE_NAME"] = qro_t1->value("TRADE_NAME").toString();//药品商品名
            m["SPECS"] = qro_t1->value("SPECS").toString();//规格
            m["DRUG_TYPE"] = qro_t1->value("DRUG_TYPE").toString();//药品类别
            m["DRUG_QUALITY"] = qro_t1->value("DRUG_QUALITY").toString();//药品性质
            m["RETAIL_PRICE"] = qro_t1->value("RETAIL_PRICE").toString();//零售价
            m["WHOLESALE_PRICE"] = qro_t1->value("WHOLESALE_PRICE").toString();//批发价
            m["PURCHASE_PRICE"] = qro_t1->value("PURCHASE_PRICE").toString();//实进价
            m["PACK_UNIT"] = qro_t1->value("PACK_UNIT").toString();//包装单位
            m["PACK_QTY"] = qro_t1->value("PACK_QTY").toString();//包装数
            m["MIN_UNIT"] = qro_t1->value("MIN_UNIT").toString();//最小单位
            m["SHOW_FLAG"] = qro_t1->value("SHOW_FLAG").toString();//显示的单位标记
            QDateTime dt = qro_t1->value("VALID_DATE").toDateTime();
            m["VALID_DATE"] = dt.toString("yyyyMMddHHmmss");//有效期
            m["STORE_SUM"] = qro_t1->value("STORE_SUM").toString();//库存数量
            m["STORE_COST"] = qro_t1->value("STORE_COST").toString();//库存金额
            m["PREOUT_SUM"] = qro_t1->value("PREOUT_SUM").toString();//预扣库存数量
            m["PREOUT_COST"] = qro_t1->value("PREOUT_COST").toString();//预扣库存金额
            m["VALID_FLAG"] = qro_t1->value("VALID_FLAG").toString();//有效性标志 0 在用 1 停用 2 废弃
            m["PRODUCER_CODE"] = qro_t1->value("PRODUCER_CODE").toString();//生产厂家
            m["LAST_MONTH_NUM"] = qro_t1->value("LAST_MONTH_NUM").toString();//最近一次月结的库存量
            m["PLACE_CODE"] = qro_t1->value("PLACE_CODE").toString();//货位号
            m["STATE"] = qro_t1->value("STATE").toString();//在库状态（0-暂入库，1正式入库）
            m["MARK"] = qro_t1->value("MARK").toString();//备注
            m["OPER_CODE"] = qro_t1->value("OPER_CODE").toString();//操作员
            m["OPER_DATE"] = qro_t1->value("OPER_DATE").toString();//操作日期
            m["INVOICE_NO"] = qro_t1->value("INVOICE_NO").toString();//发票号
            m["ARK_FLAG"] = qro_t1->value("ARK_FLAG").toString();//'是否药柜管理药品 1 药柜管理 0 非药柜管理';
            m["ARK_QTY"] = qro_t1->value("ARK_QTY").toString();//药柜管理库存汇总数量
            m["manu_date"] = qro_t1->value("manu_date").toDate().toString("yyyy-MM-dd");//生产日期
            storageList << m;
        }

        qDebug()<<"storageList is : "<<storageList<<"\n";

        //处理库存数据消耗
        QMap<QString,QString> sto;
        int aplNum = qro_t2->value("out_num").toInt();   //申请出库数量

qDebug()<<"召回撤销重新出库申请数量"<<QString::number(aplNum)<<"\n";
        int opNum;                              //本批次出库数量
        foreach(sto ,storageList)
        {
            int stoNum = sto["STORE_SUM"].toInt();  //本批次库存数量
qDebug()<<"本批次库存数量"<<QString::number(stoNum)<<"\n";
            if(aplNum <= stoNum)
            {       //库存数量允许出库
                opNum = aplNum;     //出库数量 = 申请数量
            }
            else
            {                      //申请数量大于库存数量
                opNum = stoNum;     //出库数量 = 库存数量
            }


            //核减库存
            qro_t1->prepare("UPDATE PHA_COM_STORAGE SET STORE_SUM = STORE_SUM - :out_num,"
                            "STORE_COST = STORE_COST - :out_num / pack_qty * RETAIL_PRICE, "
                            "BILL_CODE = :bill_code, SERIAL_CODE = 0, TARGET_DEPT = :target_dept, "
                            "CLASS2_CODE = '0320|M1', OPER_CODE   = :oper_code, OPER_DATE   = SYSDATE"
                            " WHERE  "
                            " DRUG_DEPT_CODE = :drug_dept_code "
                            " AND DRUG_CODE  = :drug_code"
                            " AND GROUP_CODE = :group_code "
                            " and batch_no = :batch_no");
            qro_t1->bindValue(":out_num", opNum);
            qro_t1->bindValue(":bill_code", qro_t2->value("OUT_BILL_CODE").toString());
            qro_t1->bindValue(":target_dept" ,qro_t2->value("drug_dept_code").toString());
            qro_t1->bindValue(":oper_code", pub::usr_code);
            qro_t1->bindValue(":drug_dept_code", deptCode);
            qro_t1->bindValue(":drug_code", sto["DRUG_CODE"]);
            qro_t1->bindValue(":group_code", sto["GROUP_CODE"]);
            qro_t1->bindValue(":batch_no", sto["BATCH_NO"]);

            if(!qro_t1->exec())
            {
                QMessageBox::information(this,"error", qro_t1->lastError().text());
                qDebug()<<"update pha_com_storage error."<<qro_t1->lastQuery();
                delete qro_t1;
                delete qro_t2;
                pub::db_o.rollback();
                return;
            }

            //申请数量 = 申请数量 - 已完成数量
            aplNum = aplNum - opNum;

            if(aplNum == 0)
            {
                //申请数量已经完成，退出循环
                break;
            }
        }
    }
        //delete qro_t1;

//        sq = "UPDATE PHA_COM_STORAGE SET STORE_SUM = STORE_SUM - %1, "
//                      "STORE_COST = STORE_COST - %1 / pack_qty * retail_price, BILL_CODE = '%8', SERIAL_CODE = 1, "
//                      "TARGET_DEPT = '%2', CLASS2_CODE = '0320|M2', OPER_CODE = '%4', OPER_DATE   = SYSDATE  "
//                      " WHERE "
//                      " DRUG_DEPT_CODE = '%3' "
//                      " AND DRUG_CODE  = '%5' "
//                      " AND GROUP_CODE = '%6' "
//                      " and batch_no = '%7'";
//        sq = sq.arg(qro_t2->value("out_num").toString());//(":qty",  );
//        sq = sq.arg(qro_t2->value("drug_storage_code").toString());//(":tdept", );
//        sq = sq.arg(qro_t2->value("drug_dept_code").toString());//(":ddept", );
//        sq = sq.arg(pub::usr_code);//(":oper", );
//        sq = sq.arg(qro_t2->value("drug_code").toString());//(":drug_code", );
//        sq = sq.arg(qro_t2->value("group_code").toString());//(":grp", );
//        sq = sq.arg(qro_t2->value("batch_no").toString());//(":batch_no", );
//        sq = sq.arg(invo_no);//(":invo_no", );
//        qDebug()<<"变更库存数据："<<sq<<"\n";
//        if(!qro_t1->exec(sq))
//        {
//            QMessageBox::information(this,"error", "error in UPDATE PHA_COM_STORAGE ");
//            qDebug()<<qro_t1->lastError().text();
//            delete qro_t1;
//            delete qro_t2;
//            pub::db_o.rollback();
//            return;
//        }
//    }

    sq = "update fin_opb_feedetail set NOBACK_NUM = 0,CONFIRM_NUM = qty "
                 " where  invoice_no = '" + invo_no + "'";

    qDebug()<<"变更收费项目明细数据："<<sq<<"\n";
    if(!qro_t1->exec(sq))
    {
        QMessageBox::information(this,"error", "error in update fin_opb_feedetail ");
        qDebug()<<qro_t1->lastError().text();
        delete qro_t1;
        delete qro_t2;
        pub::db_o.rollback();
        return;
    }

    pub::db_o.commit();
    delete qro_t1;
    delete qro_t2;

    ui->pbTf->setEnabled(false);
    ui->pbTfzh->setEnabled(false);
    ui->pbBldy->setEnabled(false);    //病历
    ui->pb_bill_list_output->setEnabled(false);//费用清单
    ui->pbSinglePrint->setEnabled(false);    //处方
    ui->leSjh->clear();

}

void Dialog_cfdy::print_undrug(QString invoice_no)
{
    //提取发票号关联的处方信息,导入内存
    QString sq ;
    QList< QMap < QString, QString > > rec;
    QMap< QString, QString > mp;

    sq = "select item_name, specs, unit_price, qty, pack_qty, price_unit, "
         " recipe_no, clinic_code, oper_date"
         " from fin_opb_feedetail "
         " where invoice_no = '%1' and fee_code in ('005')"
         " order by recipe_no, sequence_no";//
    sq = sq.arg(invoice_no);

    qDebug()<<"提取发票号关联的处方信息:"<<sq;
    qro_undrug1->exec( sq );
    if(!qro_undrug1->next())
    {
        QMessageBox::information(this,"error","不是有效的治疗处方！");
        return;
    }

    while(true)
    {
        mp.clear();
        mp["item_name"] = qro_undrug1->value("item_name").toString();
        mp["specs"] = qro_undrug1->value("specs").toString();
        mp["unit_price"] = qro_undrug1->value("unit_price").toString();
        mp["qty"] = qro_undrug1->value("qty").toString();   //数量
        mp["pack_qty"] = qro_undrug1->value("pack_qty").toString();   //数量
        mp["price_unit"] = qro_undrug1->value("price_unit").toString();  //划价单位 ， qty / pack_qty = 划价数量
        mp["recipe_no"] = qro_undrug1->value("recipe_no").toString();
        mp["clinic_code"] = qro_undrug1->value("clinic_code").toString();
        mp["invoice_no"] = invoice_no;
        mp["oper_date"] = qro_undrug1->value("oper_date").toDate().toString("yyyy-MM-dd");

        rec << mp;

        if(!qro_undrug1->next())
        {
            break;
        }
    }

    if(mp.isEmpty())
    {
        QMessageBox::information(this,"error","收据号无效！");
        return;
    }


    QString currentRecipeNo = "";//当前处方号
    QString newRecipeNo = "";//新处方号
    double costCount = 0;   //处方金额
    int currentLine = 1;    //当前项目行数，1 - 5
    pnt->begin(prt);
    mp_page_undrug.clear(); //清空页面数据

    int count = 0;

    while(true){
        newRecipeNo = rec[count]["recipe_no"] ;
        if(currentRecipeNo != newRecipeNo)  //处方号变更，提取处方头信息进行输出
        {
            //首次进入循环时 currentRecipe_no 为空，此时不打印，只赋值
            if(!currentRecipeNo.isEmpty()){
                //非首次进入,打印前一张处方
                mp_page_undrug["金额"] = QString::asprintf("%.2f", costCount); //
                mp_page_undrug["recipe_no"] = rec[count-1]["recipe_no"];
                mp_page_undrug["clinic_code"] = rec[count-1]["clinic_code"];
                mp_page_undrug["invoice_no"] = rec[count-1]["invoice_no"];

                printPage("治疗处方");
                prt->newPage();     //处方号变更，换页
                mp_page_undrug.clear(); //清空页面数据
                currentLine = 1;    //行数
                costCount = 0;  //金额
            }
            currentRecipeNo = newRecipeNo;  //
            //通过recipe_no（处方号） 关联 met_ord_recipedetail ,获取处方诊断,医师姓名
            qro_undrug1->prepare("select doct_name,clinicdiag_name,clinicotherdiag1_name,"
                         "clinicotherdiag2_name, doct_code from met_ord_recipedetail "
                         " where recipe_no = :recipe_no");
            qro_undrug1->bindValue(":recipe_no", currentRecipeNo);//使用newRecipeNo
            if(!qro_undrug1->exec()){
                QMessageBox::information(this,"error","从 met_ord_recipedetail 提取诊断信息错误!");
                qDebug()<<qro_undrug1->lastQuery();
                break;
            }
            QStringList diagList;
            while(qro_undrug1->next()){
                mp_page_undrug["医师"] = qro_undrug1->value(0).toString();
                mp_page_undrug["doct_code"] = qro_undrug1->value("doct_code").toString();
                if(!qro_undrug1->value(1).toString().isEmpty() && diagList.indexOf(qro_undrug1->value(1).toString()) < 0)
                {
                    diagList << qro_undrug1->value(1).toString();
                }
                if(!qro_undrug1->value(2).toString().isEmpty() && diagList.indexOf(qro_undrug1->value(2).toString()) < 0)
                {
                    diagList << qro_undrug1->value(2).toString();
                }
                if(!qro_undrug1->value(3).toString().isEmpty() && diagList.indexOf(qro_undrug1->value(3).toString()) < 0)
                {
                    diagList << qro_undrug1->value(3).toString();
                }
            }
            qDebug()<<"diag list : "<< diagList<<" , diagList size is : "<< QString::number(diagList.size());
            if(diagList.size()<1)
            {
                QMessageBox::information(this,"error","无法从 met_ord_recipedetail 找到对应的信息!");
            }
            else
            {
                QString diag, zyzd;
                for (int i = 0 ; i < diagList.size() ; i++)
                {
                    if(i == 0)
                    {
                        diag += diagList[i];
                        zyzd = get_tr_diag( diagList[i], rec[count]["clinic_code"]);
                        if(!zyzd.isEmpty())
                        {
                            diag += " / " + zyzd;
                        }

                    }
                    else
                    {
                        diag += " ; " + diagList[i];
                        zyzd = get_tr_diag( diagList[i], rec[count]["clinic_code"]);
                        if(!zyzd.isEmpty())
                        {
                            diag += " / " + zyzd;
                        }
                    }

                }

                mp_page_undrug["临床诊断"] = diag;
            }

            //通过 clinic_code（门诊唯一编号）查询 fin_opr_register 获取患者信息。
            //费别， 科室，日期，病志号，姓名，性别，年龄，
            qro_undrug1->prepare("select pact_name, dept_name, trunc(reg_date) dt, card_no,"
                         "name, decode(sex_code , 'M', '男', 'F', '女') sex, birthday "
                         "from fin_opr_register where clinic_code = :cd");
            qro_undrug1->bindValue(":cd",rec[count]["clinic_code"]);
            if(!qro_undrug1->exec()){
                QMessageBox::information(this,"error","从 fin_opr_register 提取诊断信息错误!");
                qDebug()<<qro_undrug1->lastQuery();
                break;
            }
            if(!qro_undrug1->next()){
                QMessageBox::information(this,"error","从 fin_opr_register 找不到对应信息!");
                qDebug()<<qro_undrug1->lastQuery();
                break;
            }

            mp_page_undrug["科别"] = qro_undrug1->value("dept_name").toString();
            QDate dt = qro_undrug1->value("dt").toDate();
            //mp_page_undrug["日期"] = dt.toString("yyyy-MM-dd");
            mp_page_undrug["日期"] = rec[count].value("oper_date");
            mp_page_undrug["病志号"] = qro_undrug1->value("card_no").toString();
            mp_page_undrug["姓名"] = qro_undrug1->value("name").toString();
            mp_page_undrug["性别"] = qro_undrug1->value("sex").toString();
            dt = qro_undrug1->value("birthday").toDate();

            QStringList ag = pub::getNl(dt.toString("yyyy-MM-dd"));
            mp_page_undrug["年龄"] = ag[0] + ag[1];

            mp_page_undrug["处方标志"] = "普通";


            mp_page_undrug["费别"] = qro_undrug1->value("pact_name").toString();
            mp_page_undrug["名头"] = pub::hos_name;
            mp_page_undrug["处方笺"] = "处 方 笺";

        }

        mp_page_undrug["品名" + QString::number(currentLine)] = rec[count]["item_name"] ;

        QString price1 = QString::asprintf("%.1f", rec[count]["unit_price"].toDouble()); //保留1位小数
        QString price2 = QString::asprintf("%.2f", rec[count]["unit_price"].toDouble()); //保留2位小数
        QString price0 = qFuzzyCompare(price1.toDouble(), price2.toDouble()) ? price1 : price2;
        //保留1位小数和2位小数数值相等，输出1位小数形式，否则输出2位小数形式

        mp_page_undrug["价格" + QString::number(currentLine)] = "￥" + price0 ;

        //mp_page_undrug["price" + QString::number(currentLine)] = price0;
        mp_page_undrug["规格" + QString::number(currentLine)] = rec[count]["specs"];
        mp_page_undrug["数量" + QString::number(currentLine)] = rec[count]["qty"] + rec[count]["price_unit"] ;

        currentLine ++ ; //项目行数量加 1
        //下一行预填充，如有正常值，此填充将被覆盖
        mp_page_undrug["品名" + QString::number(currentLine)] = "***以下空白***";

        //QString sl, yfyl;       //品种数量，用法用量, 字串，供打印用
        int i_sl = rec[count]["qty"].toUInt() / rec[count]["pack_qty"].toInt() ;// 品种数量，数值，供计算用
        //sl = QString::number(i_sl) + rec[count]["price_unit"];
        costCount = costCount + i_sl * rec[count]["unit_price"].toDouble();     //金额累计

        count++;
        if( count  >= rec.length()){//循环结束
            mp_page_undrug["金额"] = QString::asprintf("%.2f", costCount);
            mp_page_undrug["recipe_no"] = rec[count-1]["recipe_no"];
            mp_page_undrug["clinic_code"] = rec[count-1]["clinic_code"];
            mp_page_undrug["invoice_no"] = rec[count-1]["invoice_no"];

            printPage("治疗处方");
            pnt->end(); //循环完成，结束当前页面
            break;
        }
    }
}

QString Dialog_cfdy::get_tr_diag(QString med_diag, QString clinic_code)
{
    //读取西医诊断关联的中医诊断
    QString tmp_sq, ret_str;
    tmp_sq = "select zd1, zd2, zd3, zyzd1,zyzd2,zyzd3,zyzh1,zyzh2,zyzh3"
             " from ys_bz_e_rec"
             " where clinic_code = '" + clinic_code + "'";

    qrmt->exec(tmp_sq);
    qrmt->next();

    if(qrmt->value("zd1").toString() == med_diag)
    {
        ret_str = qrmt->value("zyzd1").toString();
        if(!ret_str.isEmpty())
        {
            ret_str += "[";
            ret_str += qrmt->value("zyzh1").toString() ;
            ret_str += "]";
        }
    }
    else if(qrmt->value("zd2").toString() == med_diag)
    {
        ret_str = qrmt->value("zyzd2").toString();
        if(!ret_str.isEmpty())
        {
            ret_str += "[";
            ret_str += qrmt->value("zyzh2").toString() ;
            ret_str += "]";
        }
    }
    else if(qrmt->value("zd3").toString() == med_diag)
    {
        ret_str = qrmt->value("zyzd3").toString();
        if(!ret_str.isEmpty())
        {
            ret_str += "[";
            ret_str += qrmt->value("zyzh3").toString() ;
            ret_str += "]";
        }
    }
    else
    {
        QMessageBox::information(this, "注意", "处方项目关联的诊断在病志中无记载！");
    }

    return ret_str;
}

void Dialog_cfdy::on_pb_undrug_print_clicked()
{
    //创建日期：2024-9-27
    //修改日期：2024-10-24
    //功能描述：打印治疗处方

    QString sq, invoice_list = "'invoice_list'";
    if(!ui->rbF->isChecked())
    {
        //非发票号检索，通过 clinic_code 检索发票号
        sq = "select distinct invoice_no from fin_opb_feedetail where clinic_code = '";
        sq += clinicCode + "' and fee_code in ('005') ";
        sq += " and pay_flag = '1' and cancel_flag = '1'";
        qro_undrug0->exec(sq);

        while(qro_undrug0->next())
        {
            print_undrug( qro_undrug0->value(0).toString() );
        }
        ui->leSjh->clear();
        return;
    }
    else
    {
        if(!ui->leSjh->text().trimmed().isEmpty())
        {
            print_undrug(pub::add0(ui->leSjh->text().trimmed(),12));
            ui->leSjh->clear();
            return;
        }

    }

    //通过 ISPRINT_EXEBILL标志， 查询 fin_opb_feedetail,获取未打印,已付款的治疗费处方

    sq = "select distinct INVOICE_NO from fin_opb_feedetail "
         " where fee_date > trunc(sysdate) and trans_type = '1' "
         " and doct_dept in("
            + undrug_dept + ") and fee_code = '005' and ISPRINT_EXEBILL = '0' ";

    //qDebug()<<"查询 fin_opb_feedetail,获取未打印,已付款的治疗费处方:"<<sq;
    qro_undrug0->exec(sq);

    //消除数据提取的竞争冒险，每次延时 2s 之后开始打印，一次只打印一张处方

    undrug_invo_no = "";

    if(qro_undrug0->next())
    {
        undrug_invo_no = qro_undrug0->value(0).toString();
        tm_print_undrug->start(2000);

        qDebug()<<"查询 fin_opb_feedetail 获取未打印治疗费发票号 : "<<undrug_invo_no;

    }
}

void Dialog_cfdy::tm_print_undrug_timer()
{
    if(ui->ckb_undrug->isChecked())
    {
        print_undrug(undrug_invo_no);
    }
    QString sq = "update fin_opb_feedetail"
         " set ISPRINT_EXEBILL = '1' "
         " where invoice_no = '" + undrug_invo_no + "'";
    qro_undrug1->exec(sq);

}

void Dialog_cfdy::on_pushButton_2_clicked()
{

    ui->rbB->setChecked(true);

    QString sq;
    sq = "SELECT distinct reg.clinic_code,reg.card_no, reg.reg_date "
         " from FIN_OPR_REGISTER reg "
         " where reg_date >= to_date('2024-08-09 06:00:00','yyyy-mm-dd hh24:mi:ss') "
         " and reg.pact_name = '沈阳市保' "
         " and reg_date <= to_date('2024-09-30 20:00:00','yyyy-mm-dd hh24:mi:ss') "
         " and reg.dept_code = '0024' "
         " order by reg_date ";
    qro_undrug0->exec(sq);
    while(qro_undrug0->next())
    {

        QString clinic_code = qro_undrug0->value(0).toString();
        QString invoice_list = "'invoice_list'";
        if(!ui->rbF->isChecked())
        {
            //非发票号检索，通过 clinic_code 检索发票号
            sq = "select distinct invoice_no from fin_opb_feedetail where clinic_code = '";
            sq += clinic_code + "' and fee_code in ('005') ";
            sq += " and pay_flag = '1' and cancel_flag = '1'";
            qro_undrug1->exec(sq);

            while(qro_undrug1->next())
            {
                print_undrug( qro_undrug1->value(0).toString() );
            }
            ui->leSjh->clear();
        }
    }
    QMessageBox::information(this, "note", " All done !");
}

void Dialog_cfdy::on_pb_bill_list_output_clicked()
{
    if(clinicCode.isEmpty())
    {
        QMessageBox::information(this, "注意", "门诊号无效！");
        return;
    }

    ui->pb_bill_list_output->setEnabled(false);
    qApp->processEvents();
    tj_bill_list_output::bill_list_output(clinicCode,
                        ui->ckb_bill_check_fee->isChecked(),
                        !ui->ckb_no_print_out->isChecked());
    ui->pb_bill_list_output->setEnabled(true);
}

void Dialog_cfdy::on_cbbCheck_currentTextChanged(const QString &arg1)
{
    //此变量用于通知其它页面，本页打印不需要
    pub::druged_oper_code = arg1;
}

void Dialog_cfdy::on_cbbDelivery_currentTextChanged(const QString &arg1)
{
    //此变量用于通知其它页面，本页打印不需要
    pub::send_oper_code = arg1;
}

void Dialog_cfdy::on_pb_cancel_bill_search_clicked()
{
    QStringList bill_no;
    QString tip;

    QString sq = " select distinct bill_no from met_nui_cancelitem "
                 " where charge_flag ='0' ";//order by APPLY_NO desc";

    qDebug()<<"提取 met_nui_cancelitem 收款处未确认记录："<<sq<<"\n";
    qro->exec(sq);
    if(qro->next())
    {
        bill_no << qro->value(0).toString();
    }
    else
    {
        QMessageBox::information(this, "注意", "未找到药局已退，收款处未确认的发票号。");
        return;
    }

    int bill_count = 1;

    while (true)
    {
        if( !qro->next())
        {
            break;
        }

        if(bill_count < 5)
        {
            bill_no << qro->value(0).toString();
        }

        bill_count ++ ;

    }

    tip = "可召回发票 " + QString::number(bill_count) + " 张,";
    if(bill_count > 5)
    {
        tip += "其中 5 张发票号：";
    }

    tip += "\n" + bill_no.join(",") ;

    QMessageBox::information(this,"错误",tip);

    ui->leSjh->setText(bill_no[0]);
    ui->rbF->setChecked(true);
    on_pbSearch_clicked();
}
